Skip to content

Commit

Permalink
better web site
Browse files Browse the repository at this point in the history
  • Loading branch information
fankaiLiu committed Oct 21, 2023
1 parent eab5807 commit ea7977b
Show file tree
Hide file tree
Showing 10 changed files with 362 additions and 160 deletions.
10 changes: 10 additions & 0 deletions src/template/src/main_template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ async fn main() {
"swagger-ui: https://{}/swagger-ui",
&CFG.server.address.replace("0.0.0.0", "127.0.0.1")
);
{{#if is_web_site}}
{{#if need_db_conn}}
println!("login page: https://{}/login", &CFG.server.address.replace("0.0.0.0", "127.0.0.1"));
{{/if}}
{{/if}}
let config = RustlsConfig::new(
Keycert::new()
.cert(CERT_KEY.cert.clone())
Expand All @@ -68,6 +73,11 @@ async fn main() {
"swagger-ui: http://{}/swagger-ui",
&CFG.server.address.replace("0.0.0.0", "127.0.0.1")
);
{{#if is_web_site}}
{{#if need_db_conn}}
println!("login page: http://{}/login", &CFG.server.address.replace("0.0.0.0", "127.0.0.1"));
{{/if}}
{{/if}}
let acceptor = TcpListener::new(&CFG.server.address).bind().await;
let server = Server::new(acceptor).serve_with_graceful_shutdown(
service,
Expand Down
1 change: 1 addition & 0 deletions src/template/src/middleware/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct JwtClaims {
exp: i64,
}

#[allow(dead_code)]
pub fn jwt_hoop() -> JwtAuth<JwtClaims, ConstDecoder> {
let auth_handler: JwtAuth<JwtClaims, _> = JwtAuth::new(ConstDecoder::from_secret(
CFG.jwt.jwt_secret.to_owned().as_bytes(),
Expand Down
114 changes: 93 additions & 21 deletions src/template/src/routers/mod.hbs
Original file line number Diff line number Diff line change
@@ -1,46 +1,37 @@
{{#if need_db_conn}}
{{#if is_web_site}}
use crate::middleware::jwt::jwt_hoop;
{{/if}}
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};

use self::{
demo::hello,
{{#if need_db_conn}}
{{#if is_web_site}}
user::{
delete_user,login_page, post_add_user, post_login, post_update_user,
delete_user, get_users, login_page, post_add_user, post_login, put_update_user,
user_list_page,
},
{{else}}
user::{
delete_user, get_users, post_add_user, post_login, post_update_user,
},
{{/if}}
{{/if}}
};
pub mod demo;
{{#if need_db_conn}}
pub mod user;
{{/if}}

pub fn router() -> Router {
{{#if is_web_site}}
{{#if need_db_conn}}
let mut no_auth_routers = vec![
Router::with_path("login").get(login_page),
Router::with_path("/api/login").post(post_login),
];

let mut need_auth_routers = vec![
Router::with_path("users")
.get(user_list_page),
Router::with_path("/api/users").get(get_users)
.post(post_add_user)
.get(user_list_page),
Router::with_path("/api/users")
.get(get_users)
.put(post_update_user)
.push(Router::with_path("<id>").delete(delete_user)),
.push(
Router::with_path("<id>")
.put(put_update_user)
.delete(delete_user),
),
];
let router = Router::new()
.hoop(Logger::new())
Expand All @@ -52,10 +43,91 @@ pub fn router() -> Router {
.append(&mut need_auth_routers)
.hoop(jwt_hoop()),
);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
}
{{else}}
use crate::middleware::jwt::jwt_hoop;
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};

use self::{
demo::hello,
user::{
delete_user, get_users, post_add_user, post_login, put_update_user,
},
};
pub mod demo;
pub mod user;

pub fn router() -> Router {
let mut no_auth_routers = vec![
Router::with_path("/api/login").post(post_login),
];

let mut need_auth_routers = vec![
Router::with_path("/api/users").get(get_users)
.post(post_add_user)
.push(
Router::with_path("<id>")
.put(put_update_user)
.delete(delete_user),
),
];
let router = Router::new()
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello)
.append(&mut no_auth_routers)
.push(
Router::new()
.append(&mut need_auth_routers)
.hoop(jwt_hoop()),
);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
}
{{/if}}
{{/if}}
{{else}}
{{#if is_web_site}}
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};
use self::demo::hello;
pub mod demo;
pub fn router() -> Router {
let router = Router::new()
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
}
}
{{else}}
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};
use self::demo::hello;
pub mod demo;
pub fn router() -> Router {
let router = Router::new()
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
}
{{/if}}
{{/if}}
113 changes: 76 additions & 37 deletions src/template/src/routers/user.hbs
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
{{#if is_web_site}}
use crate::{
app_error::AppResult,
app_response::{ErrRes, Res},
dtos::user::{UserAddRequest, UserLoginRequest, UserLoginResponse, UserUpdateRequest},
middleware::jwt::decode_token,
services::user,
};
use askama::Template;
use salvo::{
endpoint,
http::cookie::Cookie,
oapi::extract::{JsonBody, PathParam},
writing::{Redirect, Text},
Request, Response,
};

#[derive(Template)]
#[template(path = "login.html")]
struct LoginTemplate {}

#[endpoint]
#[endpoint( tags("comm"),)]
pub async fn login_page(res: &mut Response) -> AppResult<()> {
let cookies = res.cookies();
let cookie = cookies.get("jwt_token");
Expand All @@ -19,8 +35,23 @@ pub async fn login_page(res: &mut Response) -> AppResult<()> {
res.render(Text::Html(hello_tmpl.render().unwrap()));
Ok(())
}
#[endpoint( tags("comm"),)]
pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
let result: AppResult<UserLoginResponse> = user::login(req.0).await;
match result {
Ok(data) => {
let jwt_token = data.token.clone();
let cookie = Cookie::build("jwt_token", jwt_token)
.path("/")
.http_only(true)
.finish();
res.add_cookie(cookie);
}
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
#[endpoint( tags("users"))]
pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
let result = user::add_user(req.0).await;
match result {
Expand All @@ -29,7 +60,10 @@ pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
}
}

#[endpoint]
#[endpoint( tags("users"),
parameters(
("id", description = "user id"),
))]
pub async fn put_update_user(req: &mut Request, res: &mut Response) {
let req: UserUpdateRequest = req.extract().await.unwrap();
let result = user::update_user(req).await;
Expand All @@ -39,7 +73,7 @@ pub async fn put_update_user(req: &mut Request, res: &mut Response) {
}
}

#[endpoint]
#[endpoint( tags("users"),)]
pub async fn delete_user(id: PathParam<String>, res: &mut Response) {
let result = user::delete_user(id.0).await;
match result {
Expand All @@ -48,7 +82,7 @@ pub async fn delete_user(id: PathParam<String>, res: &mut Response) {
}
}

#[endpoint]
#[endpoint( tags("users"),)]
pub async fn get_users(res: &mut Response) {
let result = user::users().await;
match result {
Expand All @@ -57,22 +91,6 @@ pub async fn get_users(res: &mut Response) {
}
}

#[endpoint]
pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
let result: Result<crate::dtos::user::UserLoginResponse, crate::app_error::AppError> =
user::login(req.0).await;
match result {
Ok(data) => {
let jwt_token = data.token.clone();
let cookie = Cookie::build("jwt_token", jwt_token)
.path("/")
.http_only(true)
.finish();
res.add_cookie(cookie);
}
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}
#[derive(Template)]
#[template(path = "user_list_page.html")]
pub struct UserListPageTemplate {}
Expand All @@ -97,19 +115,36 @@ pub async fn user_list_page(req: &mut Request, res: &mut Response) -> AppResult<
Ok(())
}
{{else}}
use salvo::{
endpoint,
oapi::extract::{FormBody, JsonBody},
Response,
};
use crate::{
app_error::AppResult,
app_response::{ErrRes, Res},
dtos::user::{
UserAddRequest, UserDeleteRequest, UserLoginRequest, UserUpdateRequest,
},
dtos::user::{UserAddRequest, UserLoginRequest, UserLoginResponse, UserUpdateRequest},
services::user,
};
#[endpoint]
use salvo::{
endpoint,
http::cookie::Cookie,
oapi::extract::{JsonBody, PathParam},
Request, Response,
};

#[endpoint( tags("comm"),)]
pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
let result: AppResult<UserLoginResponse> = user::login(req.0).await;
match result {
Ok(data) => {
let jwt_token = data.token.clone();
let cookie = Cookie::build("jwt_token", jwt_token)
.path("/")
.http_only(true)
.finish();
res.add_cookie(cookie);
}
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint( tags("users"))]
pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
let result = user::add_user(req.0).await;
match result {
Expand All @@ -118,25 +153,29 @@ pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
}
}

#[endpoint]
pub async fn post_update_user(req: JsonBody<UserUpdateRequest>, res: &mut Response) {
let result = user::update_user(req.0).await;
#[endpoint( tags("users"),
parameters(
("id", description = "user id"),
))]
pub async fn put_update_user(req: &mut Request, res: &mut Response) {
let req: UserUpdateRequest = req.extract().await.unwrap();
let result = user::update_user(req).await;
match result {
Ok(data) => Res::with_data(data).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
pub async fn delete_user(req: JsonBody<UserDeleteRequest>, res: &mut Response) {
let result = user::delete_user(req.0).await;
#[endpoint( tags("users"),)]
pub async fn delete_user(id: PathParam<String>, res: &mut Response) {
let result = user::delete_user(id.0).await;
match result {
Ok(_) => Res::with_data(()).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
#[endpoint( tags("users"),)]
pub async fn get_users(res: &mut Response) {
let result = user::users().await;
match result {
Expand Down
Loading

0 comments on commit ea7977b

Please sign in to comment.