Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复一些重复查询, clippy warn #24

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ Cargo.lock

/target


#log
*.log
/idea
/.idea
/.fleet
/logs


/.vscode
19 changes: 13 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
rbs = { version = "4.5" }
rbatis = { version = "4.5", features = [] }
rbdc-sqlite = { version = "4.5" }
#rbdc-mysql = { version = "4.5" }
# rbdc-sqlite = { version = "4.5" }
rbdc-mysql = { version = "4.5" }
#rbdc-pg = { version = "4.5" }
#rbdc-mssql = { version = "4.5" }

Expand All @@ -22,7 +22,7 @@ log = "0.4"
#fast_log enable features = ["lz4", "zip", "gzip"], and edit src/config/log.rs fn choose_packer(),edit application.json5 add log_pack_compress: "zip"
fast_log = { version = "1.6", features = ["mmap"] }

axum = {version = "0.7.4",features = ["macros"]}
axum = {version = "0.7.5",features = ["macros"]}
tower-http = {version = "0.5.2",features = ["fs","cors"]}
#redis
redis = { version = "0.25.2", features = ["tokio-comp"] }
Expand All @@ -31,22 +31,29 @@ jsonwebtoken = "9.2"
md5 = "0.7"
#captcha
captcha = "0.0.9"
#http client,use rust-tls replace to native tls
#http client,use rust-tls replace to native tlss
reqwest = { version = "0.12", features = ["json"] }
#image code
image = "0.25.0"
#lazy
once_cell = "1.9"
futures-util = "0.3.21"
parking_lot = "0.12.1"
sqlparser = "0.44.0"
sqlparser = "0.46.0"
json5 = "0.4"

# me
# inventory = "0.3.15"
bcrypt = "0.15"
fastdate = "0.3"
axum-otel-metrics = "0.8.1"


[build-dependencies]
json5 = "0.4"
serde = { version = "1.0", features = ["derive"] }

[profile.release]
lto = true
opt-level = 3
codegen-units = 1
codegen-units = 1
25 changes: 25 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# todo

- 登陆多次查询角色和权限,前端不需要再请求sys_user_info或者sys_login不需要返回角色和权限,只需要返回token
/admin/sys_login
/admin/sys_user_info

- 账号,角色,权限管理页面查询要优化,不用把所有关联都查询出来,前端可以在点开编辑的时候再查询关联数据

# 更新内容
### 1
- ServiceContext 改为Default注入, service 实例 Default::default()
- fast_log 增加一个log_farmat,修改输出文件行号的格式,方便调试
- 密码加密bcrypt
### 2
- SysUserVO和SignInVO去掉password字段
- 更新用户表时,先删除角色再增加角色,改为先更新,再插入
- 修复登陆失败3次时间限制,如果再失败,不要清除次数
- 修复查询用户多次查询角色
### 3
- 增加监控 axum-otel-metrics
- 修复查询用户get_user_info多次查询角色权限
- 修复token验证权限
- 修复查询角色没有用到缓存
### 4
- 优化Error
13 changes: 6 additions & 7 deletions application.json5
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
{
debug: true,
server_name: "abs_admin",
server_url: "0.0.0.0:8000",
server_url: "127.0.0.1:8000",
//choose ("mem","redis")
cache_type: "mem",
cache_type: "redis",
//cache_type=“redis” enabled
redis_url: "redis://127.0.0.1:6379",
redis_url: "redis://:[email protected]:6379",
//choose database (need add `rbdc-<database> = { version = "*" }` of Cargo.toml)
//db_url: "sqlite://target/sqlite.db",
//db_url: "mysql://root:123456@localhost:3306/test",
//db_url: "postgres://postgres:123456@localhost:5432/postgres",
//db_url: "mssql://SA:TestPass!123456@localhost:1433/test",
db_url: "sqlite://target/sqlite.db",
db_url: "mysql://root:[email protected]:3306/abs_admin",
// database pool len
db_pool_len: 32,
//pool get timeout
db_pool_timeout: 60,
//log dir, you can use "target/logs/abc.log" default is "target/logs/"
log_dir: "target/logs/",
log_dir: "target/logs.nosync/",
//log size-KB,MB,GB
log_temp_size: "100MB",
//log type,choose one of ("mmap","file")
log_type: "file",
log_type: "mmap",
//Log channel length: null for unbounded queue, non-null for bounded queue (better performance)
log_chan_len: 100000,
// Optional log packaging formats: "" (keep as .log), "gzip" (GZip compressed), "zip" (ZIP compressed), "lz4" (LZ4 compressed (very fast))
Expand Down Expand Up @@ -75,7 +75,6 @@
"role_user_cannot_empty": "添加角色时用户和角色不能为空",
"user_not_exists": "用户不存在",
"user_and_name_cannot_empty": "用户名和姓名不能为空",
"user_cannot_find": "找不到用户",
"account_not_exists": "账号不存在",
"account_disabled": "账户被禁用",
"password_empty": "密码为空",
Expand Down
91 changes: 91 additions & 0 deletions application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@

debug: true,
server_name: "abs_admin",
server_url: "127.0.0.1:8000",
# choose ("mem","redis")
cache_type: "redis",
# cache_type=“redis” enabled
redis_url: "redis:\\:[email protected]:6379",
# choose database (need add `rbdc-<database> = { version = "*" }` of Cargo.toml)
# db_url: "sqlite:\\target/sqlite.db",
# db_url: "mysql:\\root:123456@localhost:3306/test",
# db_url: "postgres:\\postgres:123456@localhost:5432/postgres",
# db_url: "mssql:\\SA:TestPass!123456@localhost:1433/test",
db_url: "mysql:\\root:[email protected]:3306/abs_admin",
# database pool len
db_pool_len: 32,
# pool get timeout
db_pool_timeout: 60,
# log dir, you can use "target/logs/abc.log" default is "target/logs/"
log_dir: "target/logs/",
# log size-KB,MB,GB
log_temp_size: "100MB",
# log type,choose one of ("mmap","file")
log_type: "mmap",
# Log channel length: null for unbounded queue, non-null for bounded queue (better performance)
log_chan_len: 100000,
# Optional log packaging formats: "" (keep as .log), "gzip" (GZip compressed), "zip" (ZIP compressed), "lz4" (LZ4 compressed (very fast))
# The following options need to be enabled:
# Inside the toml file, add to 'fast_log': fast_log = { version = "1.5", features = ["lz4", "zip", "gzip"]}
# In src/config/log.rs, uncomment the section under fn choose_packer()
# In application.json5, add: log_pack_compress: "zip"
log_pack_compress: "",
# Log rolling retention options:
# Retain all logs: All
# Retain logs by time (in seconds): KeepTime(i64)
# Retain logs by version: KeepNum(i64)
log_rolling_type: "KeepNum(60)",
# log_level: off,info,error,warn,debug,trace
log_level: "debug",
# jwt_secret
jwt_secret: "abs_admin",
# jwt to the exp (in seconds) default 30 minutes
jwt_exp : 1800,
# Jwt resolution determines whether the expiration time is less than give minutes (default 10 minutes) and automatically renews the contract
jwt_refresh_token : 600,
# SMS channel caching
# The system first puts the data into the 'sms:send:' queue
# Third-party SMS SDK or program needs to retrieve and send from the queue
# Receipts obtained are stored in 'sms:resp:*' format
sms_cache_send_key_prefix: "sms:send:",
# Login failure rejection policy: Retry count limit (0 for unlimited attempts)
login_fail_retry: 3,
# Wait time (in seconds) for login after exceeding the retry count limit for login failures
login_fail_retry_wait_sec: 30,
# white_list_api
white_list_api: ["/","/admin/sys_login","/admin/captcha"],
# Garbage data timeout, unit: days (data that exceeds the timeout for deletion will be permanently removed)
trash_recycle_days: 90,
# / format datetime.you can choose any ['YYYY-MM-DD hh:mm:ss.000000', 'YYYY-MM-DD hh:mm:ss']
datetime_format: "YYYY-MM-DD hh:mm:ss",
# error map <code : error_msg>
errors:
"-1": "未知错误",
"empty": "缺少参数",
"arg.name_empty": "权限名字不能为空",
"arg.permission_empty": "权限不能为空",
"access_token_empty": "令牌不能为空",
"access_denied": "无权限访问",
"account_empty": "账户不能为空",
"cannot_disable_admin": "不能禁用超级管理员",
"dict_exists": "字典已存在",
"permission_exists": "权限已存在",
"role_id_empty": "角色id不能为空",
"please_send_code": "请发送验证码",
"role_user_cannot_empty": "添加角色时用户和角色不能为空",
"user_not_exists": "用户不存在",
"user_and_name_cannot_empty": "用户名和姓名不能为空",
"account_not_exists": "账号不存在",
"account_disabled": "账户被禁用",
"password_empty": "密码为空",
"password_error": "密码不正确",
"vcode_error": "验证码不正确",
# if have '{}',you must use before ',' string to equal code/msg
"req_frequently": "操作过于频繁,请等待{}秒后重试",
"id_empty": "id不能为空"






11 changes: 8 additions & 3 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/*
* @Date: 2024-05-21 21:36:59
* @LastEditTime: 2024-05-21 22:28:23
*/

use std::fs::OpenOptions;
use std::io::{Read, Write};

Expand All @@ -19,14 +24,14 @@ fn main() {
let mut data = String::new();
let mut f = OpenOptions::new()
.write(true)
.create(true)
.open("target/driver.rs")
.create(true).truncate(true)
.open("target/driver.rs")//
.unwrap();
_ = f.read_to_string(&mut data);

let db_index = config
.db_url
.find(":")
.find(':')
.expect("db_url must be '<database>://xxxx'");
let mut db_name = &config.db_url[..db_index];
if db_name == "postgres" {
Expand Down
46 changes: 28 additions & 18 deletions src/config/config.rs → src/config/app_config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::collections::HashMap;
use rbs::to_value;

use crate::error::Error;

/// Config
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize,Default)]
pub struct ApplicationConfig {
pub debug: bool,
pub server_url: String,
Expand Down Expand Up @@ -31,18 +33,15 @@ pub struct ApplicationConfig {
pub error_infos: Option<HashMap<String, String>>,
}

impl Default for ApplicationConfig {
fn default() -> Self {
let js_data = include_str!("../../application.json5");
impl ApplicationConfig {
pub fn new() -> Self {
// let js_data = include_str!("../../application.json5");
let js_data = std::fs::read_to_string("application.json5").unwrap();
//load config
let mut result: ApplicationConfig =
json5::from_str(js_data).expect("load config file fail");
json5::from_str(&js_data).expect("load config file fail");
result.init_infos();
if cfg!(debug_assertions) {
result.debug = true;
} else {
result.debug = false;
}
result.debug = cfg!(debug_assertions);
if result.debug {
println!("[abs_admin] {}", to_value!(&result));
println!("[abs_admin] ///////////////////// Start On Debug Mode ////////////////////////////");
Expand All @@ -51,25 +50,33 @@ impl Default for ApplicationConfig {
}
result
}
}

impl ApplicationConfig {
pub fn get_error_info(&self, code: &str) -> String {
match self.errors.get(code) {
None => match self.errors.get("-1") {
None => "unknown error".to_string(),
Some(v) => v.to_string(),
None => "unknown error".to_string() ,
Some(v) =>v.to_string(),
},
Some(v) => v.as_str().to_string(),
Some(v) =>v.to_string() ,
}
}

pub fn get_error(&self, code: &str) -> Error {
let error_info = self.get_error_info(code);
Error::CE(code.to_string(), error_info)
}

pub fn get_error_arg(&self, code: &str, msg: String) -> Error {
let error_info = self.get_error_info(code);
Error::CE(code.to_string(), error_info.replace("{}", &msg))
}

pub fn init_infos(&mut self) {
self.error_infos = Some(HashMap::new());
for (k, error) in &self.errors {
let mut error = error.to_string();
if error.contains(",") {
error = error[0..error.find(",").unwrap()].to_string();
if error.contains(',') {
error = error[0..error.find(',').unwrap()].to_string();
}
self.error_infos
.as_mut()
Expand All @@ -82,6 +89,9 @@ impl ApplicationConfig {
#[macro_export]
macro_rules! error_info {
($code: expr) => {
$crate::service::CONTEXT.config.get_error_info($code)
$crate::service::CONTEXT.config.get_error($code)
};
($code: expr, $msg: expr) => {
$crate::service::CONTEXT.config.get_error_arg($code, $msg)
};
}
Loading