chore: re-format file

This commit is contained in:
Maulana Sodiqin
2025-02-16 01:09:55 +07:00
parent 53414687ff
commit 9abab01b9c
14 changed files with 373 additions and 12519 deletions
+1
View File
@@ -4,6 +4,7 @@
# Nix
/.direnv
Cargo.nix
# Environment
.envrc
Generated
+153 -1
View File
@@ -28,6 +28,18 @@ dependencies = [
"version_check",
]
[[package]]
name = "ahash"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "aho-corasick"
version = "1.1.3"
@@ -379,6 +391,16 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "chumsky"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eebd66744a15ded14960ab4ccdbfb51ad3b81f51f3f04a80adac98c985396c9"
dependencies = [
"hashbrown 0.14.5",
"stacker",
]
[[package]]
name = "combine"
version = "4.6.7"
@@ -548,6 +570,22 @@ dependencies = [
"serde",
]
[[package]]
name = "email-encoding"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea3d894bbbab314476b265f9b2d46bf24b123a36dd0e96b06a1b49545b9d9dcc"
dependencies = [
"base64",
"memchr",
]
[[package]]
name = "email_address"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
[[package]]
name = "encoding_rs"
version = "0.8.35"
@@ -798,7 +836,17 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash",
"ahash 0.7.8",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash 0.8.11",
"allocator-api2",
]
[[package]]
@@ -866,6 +914,17 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "hostname"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c7c7c8ac16c798734b8a24560c1362120597c40d5e1459f09498f8f6c8f2ba"
dependencies = [
"cfg-if",
"libc",
"windows",
]
[[package]]
name = "http"
version = "1.2.0"
@@ -1117,6 +1176,7 @@ dependencies = [
"axum",
"chrono",
"jsonwebtoken",
"lettre",
"log",
"redis",
"sea-orm",
@@ -1189,6 +1249,34 @@ dependencies = [
"spin",
]
[[package]]
name = "lettre"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e882e1489810a45919477602194312b1a7df0e5acc30a6188be7b520268f63f8"
dependencies = [
"async-trait",
"base64",
"chumsky",
"email-encoding",
"email_address",
"fastrand",
"futures-io",
"futures-util",
"hostname",
"httpdate",
"idna",
"mime",
"native-tls",
"nom",
"percent-encoding",
"quoted_printable",
"socket2",
"tokio",
"tokio-native-tls",
"url",
]
[[package]]
name = "libc"
version = "0.2.169"
@@ -1283,6 +1371,12 @@ dependencies = [
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.3"
@@ -1337,6 +1431,16 @@ dependencies = [
"tempfile",
]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
@@ -1664,6 +1768,15 @@ dependencies = [
"yansi",
]
[[package]]
name = "psm"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f58e5423e24c18cc840e1c98370b3993c6649cd1678b4d24318bcf0a083cbe88"
dependencies = [
"cc",
]
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -1693,6 +1806,12 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "quoted_printable"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "640c9bd8497b02465aeef5375144c26062e0dcd5939dfcbb0f5db76cb8c17c73"
[[package]]
name = "radium"
version = "0.7.0"
@@ -2469,6 +2588,19 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "stacker"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d08feb8f695b465baed819b03c128dc23f57a694510ab1f06c77f763975685e"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.59.0",
]
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -2682,6 +2814,16 @@ dependencies = [
"syn 2.0.98",
]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
dependencies = [
"native-tls",
"tokio",
]
[[package]]
name = "tokio-stream"
version = "0.1.17"
@@ -3009,6 +3151,16 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "windows"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be"
dependencies = [
"windows-core",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.52.0"
-12353
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -16,6 +16,7 @@ chrono = "0.4.39"
utoipa = { version = "5.3.1", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] }
redis = "0.28.2"
lettre = { version = "0.11.12", features = ["tokio1-native-tls"] }
[profile.release]
lto = "fat"
+15 -15
View File
@@ -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
View File
@@ -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
View File
@@ -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),
}
}
+68 -62
View File
@@ -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
}
+42
View File
@@ -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))
}
}
}
+2
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}
+31 -29
View File
@@ -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()
}