chore: re-format file
This commit is contained in:
+15
-15
@@ -3,35 +3,35 @@ use utoipa::{IntoParams, ToSchema};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MessageResponseDto {
|
||||
pub message: String,
|
||||
pub version: String,
|
||||
pub message: String,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
|
||||
pub struct MetaRequestDto {
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub search: Option<String>,
|
||||
pub sort_by: Option<String>,
|
||||
pub order: Option<String>,
|
||||
pub filter: Option<String>,
|
||||
pub filter_by: Option<String>,
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub search: Option<String>,
|
||||
pub sort_by: Option<String>,
|
||||
pub order: Option<String>,
|
||||
pub filter: Option<String>,
|
||||
pub filter_by: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, IntoParams)]
|
||||
pub struct MetaResponseDto {
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub total: Option<u64>,
|
||||
pub page: Option<u64>,
|
||||
pub per_page: Option<u64>,
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ResponseSuccessDto<T: Serialize> {
|
||||
pub data: T,
|
||||
pub data: T,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct ResponseListSuccessDto<T: Serialize> {
|
||||
pub data: T,
|
||||
pub meta: Option<MetaResponseDto>,
|
||||
pub data: T,
|
||||
pub meta: Option<MetaResponseDto>,
|
||||
}
|
||||
|
||||
+17
-16
@@ -1,24 +1,25 @@
|
||||
use argon2::{
|
||||
password_hash::{
|
||||
rand_core::OsRng, Error, PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
|
||||
},
|
||||
Argon2,
|
||||
password_hash::{
|
||||
rand_core::OsRng, Error, PasswordHash, PasswordHasher, PasswordVerifier,
|
||||
SaltString,
|
||||
},
|
||||
Argon2,
|
||||
};
|
||||
|
||||
pub fn hash_password(password: &str) -> Result<String, Error> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)?
|
||||
.to_string();
|
||||
Ok(password_hash)
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)?
|
||||
.to_string();
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
pub fn verify_password(password: &str, hash: &str) -> Result<bool, Error> {
|
||||
let parsed_hash = PasswordHash::new(hash)?;
|
||||
let argon2 = Argon2::default();
|
||||
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
let parsed_hash = PasswordHash::new(hash)?;
|
||||
let argon2 = Argon2::default();
|
||||
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
+16
-16
@@ -5,21 +5,21 @@ use tokio::net::TcpListener;
|
||||
|
||||
pub async fn axum_init<F, Fut>(router_fn: F)
|
||||
where
|
||||
F: Fn() -> Fut,
|
||||
Fut: Future<Output = Router>,
|
||||
F: Fn() -> Fut,
|
||||
Fut: Future<Output = Router>,
|
||||
{
|
||||
let router = router_fn().await;
|
||||
let addr = SocketAddr::from((
|
||||
[0, 0, 0, 0],
|
||||
env::var("PORT")
|
||||
.unwrap_or("3000".to_string())
|
||||
.parse()
|
||||
.unwrap(),
|
||||
));
|
||||
let listener = TcpListener::bind(&addr).await.unwrap();
|
||||
println!("Listening on http://{}", addr);
|
||||
match serve(listener, router).await {
|
||||
Ok(_) => println!("Server stopped gracefully."),
|
||||
Err(err) => println!("Server encountered an error: {}", err),
|
||||
}
|
||||
let router = router_fn().await;
|
||||
let addr = SocketAddr::from((
|
||||
[0, 0, 0, 0],
|
||||
env::var("PORT")
|
||||
.unwrap_or("3000".to_string())
|
||||
.parse()
|
||||
.unwrap(),
|
||||
));
|
||||
let listener = TcpListener::bind(&addr).await.unwrap();
|
||||
println!("Listening on http://{}", addr);
|
||||
match serve(listener, router).await {
|
||||
Ok(_) => println!("Server stopped gracefully."),
|
||||
Err(err) => println!("Server encountered an error: {}", err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,80 +1,86 @@
|
||||
use axum::http::StatusCode;
|
||||
use chrono::{Duration, TimeDelta, Utc};
|
||||
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
|
||||
use jsonwebtoken::{
|
||||
decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Claims {
|
||||
pub exp: usize,
|
||||
pub iat: usize,
|
||||
pub email: String,
|
||||
pub exp: usize,
|
||||
pub iat: usize,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
pub fn encode_access_token(email: &str) -> Result<String, StatusCode> {
|
||||
let secret: String = env::var("ACCESS_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let now = Utc::now();
|
||||
let expire: TimeDelta = Duration::minutes(15);
|
||||
let exp: usize = (now + expire).timestamp() as usize;
|
||||
let iat: usize = now.timestamp() as usize;
|
||||
let claim = Claims {
|
||||
iat,
|
||||
exp,
|
||||
email: email.to_string(),
|
||||
};
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claim,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
let secret: String = env::var("ACCESS_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let now = Utc::now();
|
||||
let expire: TimeDelta = Duration::minutes(15);
|
||||
let exp: usize = (now + expire).timestamp() as usize;
|
||||
let iat: usize = now.timestamp() as usize;
|
||||
let claim = Claims {
|
||||
iat,
|
||||
exp,
|
||||
email: email.to_string(),
|
||||
};
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claim,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
pub fn decode_access_token(jwt_token: &str) -> Result<TokenData<Claims>, StatusCode> {
|
||||
let secret = env::var("ACCESS_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let result: Result<TokenData<Claims>, StatusCode> = decode(
|
||||
&jwt_token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
|
||||
result
|
||||
pub fn decode_access_token(
|
||||
jwt_token: &str,
|
||||
) -> Result<TokenData<Claims>, StatusCode> {
|
||||
let secret = env::var("ACCESS_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let result: Result<TokenData<Claims>, StatusCode> = decode(
|
||||
&jwt_token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
|
||||
result
|
||||
}
|
||||
|
||||
pub fn encode_refresh_token(email: &str) -> Result<String, StatusCode> {
|
||||
let secret: String = env::var("REFRESH_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let now = Utc::now();
|
||||
let expire: TimeDelta = Duration::days(1);
|
||||
let exp: usize = (now + expire).timestamp() as usize;
|
||||
let iat: usize = now.timestamp() as usize;
|
||||
let claim = Claims {
|
||||
iat,
|
||||
exp,
|
||||
email: email.to_string(),
|
||||
};
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claim,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
let secret: String = env::var("REFRESH_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let now = Utc::now();
|
||||
let expire: TimeDelta = Duration::days(1);
|
||||
let exp: usize = (now + expire).timestamp() as usize;
|
||||
let iat: usize = now.timestamp() as usize;
|
||||
let claim = Claims {
|
||||
iat,
|
||||
exp,
|
||||
email: email.to_string(),
|
||||
};
|
||||
encode(
|
||||
&Header::default(),
|
||||
&claim,
|
||||
&EncodingKey::from_secret(secret.as_ref()),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
pub fn decode_refresh_token(jwt_token: &str) -> Result<TokenData<Claims>, StatusCode> {
|
||||
let secret = env::var("REFRESH_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let result: Result<TokenData<Claims>, StatusCode> = decode(
|
||||
&jwt_token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
|
||||
result
|
||||
pub fn decode_refresh_token(
|
||||
jwt_token: &str,
|
||||
) -> Result<TokenData<Claims>, StatusCode> {
|
||||
let secret = env::var("REFRESH_TOKEN_SECRET")
|
||||
.unwrap_or("this-is-secret".to_string())
|
||||
.to_string();
|
||||
let result: Result<TokenData<Claims>, StatusCode> = decode(
|
||||
&jwt_token,
|
||||
&DecodingKey::from_secret(secret.as_ref()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
use lettre::message::Mailbox;
|
||||
use lettre::transport::smtp::authentication::Credentials;
|
||||
use lettre::{Message, SmtpTransport, Transport};
|
||||
use std::env;
|
||||
|
||||
pub fn send_email(
|
||||
to: &str,
|
||||
subject: &str,
|
||||
body: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let sender_email = env::var("SMTP_EMAIL")?.to_string();
|
||||
let sender_name = env::var("SMTP_NAME")?.to_string();
|
||||
let sender_password = env::var("SMTP_PASSWORD")?.to_string();
|
||||
let recipient_email = to;
|
||||
|
||||
let email = Message::builder()
|
||||
.from(Mailbox::new(
|
||||
Some(sender_name.replace("-", " ")),
|
||||
sender_email.parse()?,
|
||||
))
|
||||
.to(recipient_email.parse()?)
|
||||
.subject(subject)
|
||||
.body(body.to_string())?;
|
||||
|
||||
let smtp_credentials =
|
||||
Credentials::new(sender_email, sender_password.replace("-", " "));
|
||||
|
||||
let mailer = SmtpTransport::relay("smtp.gmail.com")?
|
||||
.credentials(smtp_credentials)
|
||||
.build();
|
||||
|
||||
match mailer.send(&email) {
|
||||
Ok(_) => {
|
||||
println!("Email sent successfully to {}", to);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Failed to send email: {}", e);
|
||||
Err(Box::new(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
pub mod argon;
|
||||
pub mod axum;
|
||||
pub mod jsonwebtoken;
|
||||
pub mod lettre;
|
||||
pub mod redis;
|
||||
pub mod seaorm;
|
||||
|
||||
pub use argon::*;
|
||||
pub use axum::*;
|
||||
pub use jsonwebtoken::*;
|
||||
pub use lettre::*;
|
||||
pub use redis::*;
|
||||
pub use seaorm::*;
|
||||
|
||||
+11
-11
@@ -3,18 +3,18 @@ use std::env;
|
||||
use redis::Client;
|
||||
|
||||
pub fn db_redis() -> redis::Connection {
|
||||
let host_name = env::var("REDIS_HOSTNAME").unwrap_or("localhost".to_string());
|
||||
let host_name = env::var("REDIS_HOSTNAME").unwrap_or("localhost".to_string());
|
||||
|
||||
let uri_scheme = if env::var("IS_TLS").is_ok() {
|
||||
"rediss"
|
||||
} else {
|
||||
"redis"
|
||||
};
|
||||
let uri_scheme = if env::var("IS_TLS").is_ok() {
|
||||
"rediss"
|
||||
} else {
|
||||
"redis"
|
||||
};
|
||||
|
||||
let url = format!("{}://{}", uri_scheme, host_name);
|
||||
let url = format!("{}://{}", uri_scheme, host_name);
|
||||
|
||||
Client::open(url)
|
||||
.expect("Invalid connection URL")
|
||||
.get_connection()
|
||||
.expect("Failed to connect to Redis")
|
||||
Client::open(url)
|
||||
.expect("Invalid connection URL")
|
||||
.get_connection()
|
||||
.expect("Failed to connect to Redis")
|
||||
}
|
||||
|
||||
+15
-15
@@ -3,19 +3,19 @@ use sea_orm::{ConnectOptions, Database, DatabaseConnection};
|
||||
use std::{env, time::Duration};
|
||||
|
||||
pub async fn db_pgsql() -> DatabaseConnection {
|
||||
let url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
let mut opt = ConnectOptions::new(&url);
|
||||
opt.max_connections(100)
|
||||
.min_connections(5)
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.idle_timeout(Duration::from_secs(3))
|
||||
.max_lifetime(Duration::from_secs(10))
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(LevelFilter::Info)
|
||||
.set_schema_search_path("public");
|
||||
match Database::connect(opt).await {
|
||||
Ok(connect) => connect,
|
||||
Err(error) => panic!("{}", error),
|
||||
}
|
||||
let url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
let mut opt = ConnectOptions::new(&url);
|
||||
opt.max_connections(100)
|
||||
.min_connections(5)
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.idle_timeout(Duration::from_secs(3))
|
||||
.max_lifetime(Duration::from_secs(10))
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(LevelFilter::Info)
|
||||
.set_schema_search_path("public");
|
||||
match Database::connect(opt).await {
|
||||
Ok(connect) => connect,
|
||||
Err(error) => panic!("{}", error),
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@ use imphnen_cms_be::{apps, libs::axum_init};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
axum_init(apps).await;
|
||||
axum_init(apps).await;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
@@ -9,35 +9,37 @@ use serde_json::json;
|
||||
use crate::{ResponseListSuccessDto, ResponseSuccessDto};
|
||||
|
||||
pub fn success_response<T: Serialize>(params: ResponseSuccessDto<T>) -> Response {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"data": params.data,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"data": params.data,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub fn success_list_response<T: Serialize>(params: ResponseListSuccessDto<T>) -> Response {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"data": params.data,
|
||||
"meta": params.meta,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
pub fn success_list_response<T: Serialize>(
|
||||
params: ResponseListSuccessDto<T>,
|
||||
) -> Response {
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"data": params.data,
|
||||
"meta": params.meta,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub fn common_response(status: StatusCode, message: &str) -> Response {
|
||||
(
|
||||
status,
|
||||
Json(json!({
|
||||
"message": message,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
(
|
||||
status,
|
||||
Json(json!({
|
||||
"message": message,
|
||||
"version": "0.1.0",
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user