From e8f43c247a6d542590735e65021fcdf20348f93d Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Thu, 16 Nov 2023 22:19:27 +0800 Subject: [PATCH 1/2] add some middleware --- src/template/config/config.hbs | 1 + src/template/src/config_template.hbs | 1 + src/template/src/middleware/cors.rs | 11 +++++++ src/template/src/middleware/jwt.rs | 2 +- src/template/src/middleware/mod.rs | 1 + src/template/src/routers/mod.hbs | 33 +++++++++++++++---- src/template/src/routers/static_routers.hbs | 5 ++- src/utils/create_project.rs | 35 +++++++++++---------- 8 files changed, 64 insertions(+), 25 deletions(-) create mode 100644 src/template/src/middleware/cors.rs diff --git a/src/template/config/config.hbs b/src/template/config/config.hbs index 2e9fadc..a1b180d 100644 --- a/src/template/config/config.hbs +++ b/src/template/config/config.hbs @@ -2,6 +2,7 @@ name = "{{project_name}}" address = "0.0.0.0:5800" ssl = false +cors_allow_origin=["https://salvo.rs"] {{#if need_db_conn}} [database] {{#if is_sea_orm_or_sqlx}} diff --git a/src/template/src/config_template.hbs b/src/template/src/config_template.hbs index c9f2626..d8ed2be 100644 --- a/src/template/src/config_template.hbs +++ b/src/template/src/config_template.hbs @@ -17,6 +17,7 @@ pub struct Configs { pub struct Server { pub name: String, pub address: String, + pub cors_allow_origin: Vec, pub ssl: bool, } {{#if need_db_conn}} diff --git a/src/template/src/middleware/cors.rs b/src/template/src/middleware/cors.rs new file mode 100644 index 0000000..a4b2f81 --- /dev/null +++ b/src/template/src/middleware/cors.rs @@ -0,0 +1,11 @@ +use salvo::cors::{AllowHeaders, AllowMethods, Cors, CorsHandler}; +use crate::config::CFG; + +pub fn cors_middleware() -> CorsHandler { + let cors_handler = Cors::new() + .allow_origin(&CFG.server.cors_allow_origin) + .allow_methods(AllowMethods::any()) + .allow_headers(AllowHeaders::any()) + .into_handler(); + cors_handler +} diff --git a/src/template/src/middleware/jwt.rs b/src/template/src/middleware/jwt.rs index cac61b0..7b9a626 100644 --- a/src/template/src/middleware/jwt.rs +++ b/src/template/src/middleware/jwt.rs @@ -14,7 +14,7 @@ pub struct JwtClaims { } #[allow(dead_code)] -pub fn jwt_hoop() -> JwtAuth { +pub fn jwt_middleware() -> JwtAuth { let auth_handler: JwtAuth = JwtAuth::new(ConstDecoder::from_secret( CFG.jwt.jwt_secret.to_owned().as_bytes(), )) diff --git a/src/template/src/middleware/mod.rs b/src/template/src/middleware/mod.rs index 9cc4bdd..bc79a1a 100644 --- a/src/template/src/middleware/mod.rs +++ b/src/template/src/middleware/mod.rs @@ -1,2 +1,3 @@ pub mod handle_404; pub mod jwt; +pub mod cors; \ No newline at end of file diff --git a/src/template/src/routers/mod.hbs b/src/template/src/routers/mod.hbs index 137ef3b..0dfc978 100644 --- a/src/template/src/routers/mod.hbs +++ b/src/template/src/routers/mod.hbs @@ -1,6 +1,6 @@ {{#if need_db_conn}} {{#if is_web_site}} -use crate::middleware::jwt::jwt_hoop; +use crate::middleware::{cors::cors_middleware, jwt::jwt_middleware}; use salvo::{ prelude::{CatchPanic, Logger, OpenApi, SwaggerUi}, Router, @@ -23,6 +23,8 @@ pub fn router() -> Router { Router::with_path("/api/login").post(post_login), ]; + let _cors_handler = cors_middleware(); + let mut need_auth_routers = vec![ Router::with_path("users") .get(user_list_page), @@ -37,6 +39,7 @@ pub fn router() -> Router { let static_routers = static_routers::create_static_routers(); no_auth_routers.extend(static_routers); let router = Router::new() + //.hoop(_cors_handler) .hoop(Logger::new()) .hoop(CatchPanic::new()) .get(hello) @@ -44,7 +47,7 @@ pub fn router() -> Router { .push( Router::new() .append(&mut need_auth_routers) - .hoop(jwt_hoop()), + .hoop(jwt_middleware()), ); let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router); router @@ -52,7 +55,7 @@ pub fn router() -> Router { .push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui")) } {{else}} -use crate::middleware::jwt::jwt_hoop; +use crate::middleware::{cors::cors_middleware, jwt::jwt_middleware}; use salvo::{ prelude::{CatchPanic, Logger, OpenApi, SwaggerUi}, Router, @@ -66,12 +69,15 @@ use self::{ }; pub mod demo; pub mod user; +mod static_routers; pub fn router() -> Router { let mut no_auth_routers = vec![ Router::with_path("/api/login").post(post_login), ]; + let _cors_handler = cors_middleware(); + let mut need_auth_routers = vec![ Router::with_path("/api/users").get(get_users) .post(post_add_user) @@ -84,6 +90,7 @@ pub fn router() -> Router { let static_routers = static_routers::create_static_routers(); no_auth_routers.extend(static_routers); let router = Router::new() + //.hoop(_cors_handler) .hoop(Logger::new()) .hoop(CatchPanic::new()) .get(hello) @@ -91,7 +98,7 @@ pub fn router() -> Router { .push( Router::new() .append(&mut need_auth_routers) - .hoop(jwt_hoop()), + .hoop(jwt_middleware()), ); let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router); router @@ -105,13 +112,20 @@ use salvo::{ prelude::{CatchPanic, Logger, OpenApi, SwaggerUi}, Router, }; +use crate::middleware::cors::cors_middleware; use self::demo::hello; pub mod demo; +mod static_routers; + pub fn router() -> Router { + let _cors_handler = cors_middleware(); + let mut static_routers = static_routers::create_static_routers(); let router = Router::new() + //.hoop(_cors_handler) .hoop(Logger::new()) .hoop(CatchPanic::new()) - .get(hello); + .get(hello) + .append(&mut static_routers); let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router); router .push(doc.into_router("/api-doc/openapi.json")) @@ -122,13 +136,20 @@ use salvo::{ prelude::{CatchPanic, Logger, OpenApi, SwaggerUi}, Router, }; +use crate::middleware::cors::cors_middleware; use self::demo::hello; pub mod demo; +mod static_routers; + pub fn router() -> Router { + let _cors_handler = cors_middleware(); + let mut static_routers = static_routers::create_static_routers(); let router = Router::new() + //.hoop(_cors_handler) .hoop(Logger::new()) .hoop(CatchPanic::new()) - .get(hello); + .get(hello) + .append(&mut static_routers); let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router); router .push(doc.into_router("/api-doc/openapi.json")) diff --git a/src/template/src/routers/static_routers.hbs b/src/template/src/routers/static_routers.hbs index 8800d53..b5a0014 100644 --- a/src/template/src/routers/static_routers.hbs +++ b/src/template/src/routers/static_routers.hbs @@ -1,6 +1,9 @@ use rust_embed::RustEmbed; +{{#if need_db_conn}} use salvo::{Router, serve_static::static_embed, endpoint, Response, http::ResBody, hyper::body::Bytes}; - +{{else}} +use salvo::{Router, endpoint, Response, http::ResBody, hyper::body::Bytes}; +{{/if}} #[derive(RustEmbed)] #[folder = "assets"] struct Assets; diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 887107b..60d61c6 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -118,11 +118,12 @@ fn write_project_file( "once_cell": "1.18.0", "salvo": { "version": "0.58", - "features": ["anyhow", "logging", "cors", "oapi", "jwt-auth", "rustls", "catch-panic","cookie"] + "features": ["anyhow", "logging", "cors", "oapi", "jwt-auth", "rustls", "catch-panic","cookie","serve-static"] }, "serde": "1.0.188", "thiserror": "1.0.48", "time": "0.3.28", + "rust-embed":"8.0.0", "tokio": { "version": "1", "features": ["full"] @@ -169,7 +170,6 @@ fn write_project_file( let mut dependencies = data["dependencies"].clone(); handle_dependencies( &mut dependencies, - is_web_site, need_db_conn, user_selected.db_type, user_selected.db_conn_type, @@ -177,6 +177,13 @@ fn write_project_file( data["dependencies"] = dependencies; let (src_path, router_path) = create_basic_file(project_path, &handlebars, &data)?; + //assets + let assets_path = project_path.join("assets"); + std::fs::create_dir_all(&assets_path)?; + //assets/favicon.ico + let favicon_bytes = include_bytes!("../template/assets/favicon.ico"); + let mut favicon_file = File::create(assets_path.join("favicon.ico"))?; + favicon_file.write_all(favicon_bytes)?; if is_web_site { //templates @@ -194,10 +201,6 @@ fn write_project_file( handlebars.render_template(handle_404_template, &data)?; let mut handle_404_file = File::create(template_path.join("handle_404.html"))?; handle_404_file.write_all(handle_404_template_rendered.as_bytes())?; - //assets - let assets_path = project_path.join("assets"); - //assets/favicon.ico - let favicon_bytes = include_bytes!("../template/assets/favicon.ico"); let mut favicon_file = File::create(assets_path.join("favicon.ico"))?; favicon_file.write_all(favicon_bytes)?; if need_db_conn { @@ -608,6 +611,10 @@ fn create_basic_file( let handle404_rendered = handlebars.render_template(handle404_template, &data)?; let mut handle404_file = File::create(middleware_path.join("handle_404.rs"))?; handle404_file.write_all(handle404_rendered.as_bytes())?; + //src/middleware/cors.rs + let cors_bytes = include_bytes!("../template/src/middleware/cors.rs"); + let mut cors_file = File::create(middleware_path.join("cors.rs"))?; + cors_file.write_all(cors_bytes)?; //config let config_path = project_path.join("config"); @@ -642,27 +649,21 @@ fn create_basic_file( let router_demo_rendered = handlebars.render_template(router_demo_template, &data)?; let mut router_demo_file = File::create(router_path.join("demo.rs"))?; router_demo_file.write_all(router_demo_rendered.as_bytes())?; + //src/router/static_routers.rs + let router_static_template = include_str!("../template/src/routers/static_routers.hbs"); + let router_static_rendered = handlebars.render_template(router_static_template, &data)?; + let mut router_static_file = File::create(router_path.join("static_routers.rs"))?; + router_static_file.write_all(router_static_rendered.as_bytes())?; Ok((src_path, router_path)) } fn handle_dependencies( dependencies: &mut serde_json::Value, - is_website: bool, need_db_conn: bool, db_type: DbType, conn_type: DbConnectionType, ) { - if is_website { - dependencies["rust-embed"] = json!({ - "version": "8.0.0", - }); - if let Some(salvo) = dependencies["salvo"].as_object_mut() { - if let Some(features) = salvo["features"].as_array_mut() { - features.push(serde_json::json!("serve-static")); - } - } - } if need_db_conn { match (conn_type, db_type) { (DbConnectionType::Sqlx, DbType::Mysql) => { From eeb7ca62948e69966347a47367193a45c07cc184 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 18 Nov 2023 22:21:40 +0800 Subject: [PATCH 2/2] fix js link --- src/template/templates/404.hbs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/template/templates/404.hbs b/src/template/templates/404.hbs index 0164311..f0bbb37 100644 --- a/src/template/templates/404.hbs +++ b/src/template/templates/404.hbs @@ -4,7 +4,11 @@ 404 {{page_not_found}} +{{#if need_db_conn}} +{{else}} + +{{/if}}