Skip to content

Commit

Permalink
Use sync::OnceLock & Bug Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
shenghui0779 committed Jan 9, 2024
1 parent 6497186 commit 10b0b95
Show file tree
Hide file tree
Showing 28 changed files with 236 additions and 287 deletions.
218 changes: 110 additions & 108 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM rust:1.67 as builder
FROM rust:1.70 as builder

WORKDIR /api_rs

Expand All @@ -19,4 +19,4 @@ EXPOSE 8000

ENTRYPOINT ["./api_rs"]

CMD ["/data/config.yaml"]
CMD ["serve", "--config", "/data/config.yaml"]
21 changes: 0 additions & 21 deletions LICENSE

This file was deleted.

20 changes: 11 additions & 9 deletions api/src/auth/identity.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use anyhow::{anyhow, Result};
use base64::{prelude::BASE64_STANDARD, Engine};
use config::Config;
use sea_orm::{DatabaseConnection, EntityTrait};
use sea_orm::EntityTrait;
use serde::{Deserialize, Serialize};

use entity::prelude::Account;
use library::crypto::aes::CBC;
use library::{
core::{cfg, db},
crypto::aes::CBC,
};

use super::Role;

Expand Down Expand Up @@ -33,7 +35,7 @@ impl Identity {
}
}

pub fn from_auth_token(cfg: &Config, token: String) -> Self {
pub fn from_auth_token(token: String) -> Self {
let cipher = match BASE64_STANDARD.decode(token) {
Err(err) => {
tracing::error!(error = ?err, "err invalid auth_token");
Expand All @@ -42,7 +44,7 @@ impl Identity {
Ok(v) => v,
};

let secret = match cfg.get_string("app.secret") {
let secret = match cfg::config().get_string("app.secret") {
Err(err) => {
tracing::error!(error = ?err, "err missing config(app.secret)");
return Identity::empty();
Expand All @@ -68,8 +70,8 @@ impl Identity {
}
}

pub fn to_auth_token(&self, cfg: &Config) -> Result<String> {
let secret = cfg.get_string("app.secret")?;
pub fn to_auth_token(&self) -> Result<String> {
let secret = cfg::config().get_string("app.secret")?;
let key = secret.as_bytes();

let plain = serde_json::to_vec(self)?;
Expand Down Expand Up @@ -99,12 +101,12 @@ impl Identity {
false
}

pub async fn check(&self, db: &DatabaseConnection) -> Result<()> {
pub async fn check(&self) -> Result<()> {
if self.id() == 0 {
return Err(anyhow!("未授权,请先登录"));
}

match Account::find_by_id(self.id()).one(db).await? {
match Account::find_by_id(self.id()).one(db::conn()).await? {
None => return Err(anyhow!("授权账号不存在")),
Some(v) => {
if v.login_token.len() == 0 || self.t != v.login_token {
Expand Down
1 change: 0 additions & 1 deletion api/src/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
pub mod identity;

#[allow(dead_code)]
pub enum Role {
Super,
Normal,
Expand Down
22 changes: 8 additions & 14 deletions api/src/controller/account.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use axum::{
extract::{Path, Query, State},
extract::{Path, Query},
Extension, Json,
};
use axum_extra::extract::WithRejection;
Expand All @@ -12,7 +12,6 @@ use serde::{Deserialize, Serialize};
use validator::Validate;

use entity::{account, prelude::*};
use library::crypto::hash::md5;
use library::result::{
rejection::IRejection,
response::{ApiErr, ApiOK, Result},
Expand All @@ -21,11 +20,9 @@ use library::util::{
helper,
time::{self, Layout},
};
use library::{core::db, crypto::hash::md5};

use crate::{
auth::{identity::Identity, Role},
AppState,
};
use crate::auth::{identity::Identity, Role};

#[derive(Debug, Validate, Deserialize, Serialize)]
pub struct ParamsCreate {
Expand All @@ -38,7 +35,6 @@ pub struct ParamsCreate {
}

pub async fn create(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
WithRejection(Json(params), _): IRejection<Json<ParamsCreate>>,
) -> Result<ApiOK<()>> {
Expand All @@ -52,7 +48,7 @@ pub async fn create(

match Account::find()
.filter(account::Column::Username.eq(params.username.clone()))
.count(&state.db)
.count(db::conn())
.await
{
Err(err) => {
Expand Down Expand Up @@ -82,7 +78,7 @@ pub async fn create(
..Default::default()
};

if let Err(err) = Account::insert(model).exec(&state.db).await {
if let Err(err) = Account::insert(model).exec(db::conn()).await {
tracing::error!(error = ?err, "err insert account");

return Err(ApiErr::ErrSystem(None));
Expand All @@ -103,15 +99,14 @@ pub struct RespInfo {
}

pub async fn info(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
Path(account_id): Path<u64>,
) -> Result<ApiOK<RespInfo>> {
if !identity.is_role(Role::Super) {
return Err(ApiErr::ErrPerm(None));
}

let model = match Account::find_by_id(account_id).one(&state.db).await {
let model = match Account::find_by_id(account_id).one(db::conn()).await {
Err(err) => {
tracing::error!(error = ?err, "err find account");
return Err(ApiErr::ErrSystem(None));
Expand Down Expand Up @@ -142,7 +137,6 @@ pub struct RespList {
}

pub async fn list(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
Query(query): Query<HashMap<String, String>>,
) -> Result<ApiOK<RespList>> {
Expand All @@ -169,7 +163,7 @@ pub async fn list(
.select_only()
.column_as(account::Column::Id.count(), "count")
.into_tuple::<i64>()
.one(&state.db)
.one(db::conn())
.await
{
Err(err) => {
Expand All @@ -184,7 +178,7 @@ pub async fn list(
.order_by(account::Column::Id, Order::Desc)
.offset(offset)
.limit(limit)
.all(&state.db)
.all(db::conn())
.await
{
Err(err) => {
Expand Down
31 changes: 13 additions & 18 deletions api/src/controller/auth.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum::extract::State;
use axum::{Extension, Json};
use axum_extra::extract::WithRejection;
use library::core::db;
use sea_orm::sea_query::Expr;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, Set};
use serde::{Deserialize, Serialize};
Expand All @@ -15,7 +15,6 @@ use library::result::{
use library::util::helper;

use crate::auth::identity::Identity;
use crate::AppState;

#[derive(Debug, Validate, Deserialize, Serialize)]
pub struct ParamsLogin {
Expand All @@ -33,7 +32,6 @@ pub struct RespLogin {
}

pub async fn login(
State(state): State<AppState>,
WithRejection(Json(params), _): IRejection<Json<ParamsLogin>>,
) -> Result<ApiOK<RespLogin>> {
if let Err(err) = params.validate() {
Expand All @@ -42,7 +40,7 @@ pub async fn login(

let ret = Account::find()
.filter(account::Column::Username.eq(params.username))
.one(&state.db)
.one(db::conn())
.await;

let record = match ret {
Expand All @@ -67,14 +65,14 @@ pub async fn login(
let now = chrono::Local::now().timestamp();
let login_token = md5(format!("auth.{}.{}.{}", model.id, now, helper::nonce(16)).as_bytes());

let auth_token =
match Identity::new(model.id, model.role, login_token.clone()).to_auth_token(&state.cfg) {
Err(err) => {
tracing::error!(error = ?err, "err identity encrypt");
return Err(ApiErr::ErrSystem(None));
}
Ok(v) => v,
};
let auth_token = match Identity::new(model.id, model.role, login_token.clone()).to_auth_token()
{
Err(err) => {
tracing::error!(error = ?err, "err identity encrypt");
return Err(ApiErr::ErrSystem(None));
}
Ok(v) => v,
};

let am = account::ActiveModel {
login_at: Set(now),
Expand All @@ -86,7 +84,7 @@ pub async fn login(
let ret_update = Account::update_many()
.filter(account::Column::Id.eq(model.id))
.set(am)
.exec(&state.db)
.exec(db::conn())
.await;

if let Err(err) = ret_update {
Expand All @@ -103,10 +101,7 @@ pub async fn login(
Ok(ApiOK(Some(resp)))
}

pub async fn logout(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
) -> Result<ApiOK<()>> {
pub async fn logout(Extension(identity): Extension<Identity>) -> Result<ApiOK<()>> {
if identity.id() == 0 {
return Ok(ApiOK(None));
}
Expand All @@ -118,7 +113,7 @@ pub async fn logout(
account::Column::CreatedAt,
Expr::value(chrono::Local::now().timestamp()),
)
.exec(&state.db)
.exec(db::conn())
.await;

if let Err(err) = ret {
Expand Down
31 changes: 14 additions & 17 deletions api/src/controller/project.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use axum::{
extract::{Path, Query, State},
extract::{Path, Query},
Extension, Json,
};
use axum_extra::extract::WithRejection;
Expand All @@ -12,20 +12,20 @@ use sea_orm::{
use serde::{Deserialize, Serialize};
use validator::Validate;

use library::result::{
rejection::IRejection,
response::{ApiErr, ApiOK, Result},
};
use library::util::{
helper,
time::{self, Layout},
};

use crate::{
auth::{identity::Identity, Role},
AppState,
use library::{
core::db,
result::{
rejection::IRejection,
response::{ApiErr, ApiOK, Result},
},
};

use crate::auth::{identity::Identity, Role};

#[derive(Debug, Validate, Deserialize, Serialize)]
pub struct ParamsCreate {
#[validate(length(min = 1, max = 8, message = "项目编号必填且长度最大为8"))]
Expand All @@ -36,7 +36,6 @@ pub struct ParamsCreate {
}

pub async fn create(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
WithRejection(Json(params), _): IRejection<Json<ParamsCreate>>,
) -> Result<ApiOK<()>> {
Expand All @@ -47,7 +46,7 @@ pub async fn create(
// 校验编号唯一性
match Project::find()
.filter(project::Column::Code.eq(params.code.clone()))
.count(&state.db)
.count(db::conn())
.await
{
Err(err) => {
Expand All @@ -73,7 +72,7 @@ pub async fn create(
..Default::default()
};

if let Err(err) = Project::insert(am).exec(&state.db).await {
if let Err(err) = Project::insert(am).exec(db::conn()).await {
tracing::error!(error = ?err, "err insert project");
return Err(ApiErr::ErrSystem(None));
}
Expand All @@ -97,7 +96,6 @@ pub struct RespList {
}

pub async fn list(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
Query(query): Query<HashMap<String, String>>,
) -> Result<ApiOK<RespList>> {
Expand Down Expand Up @@ -136,7 +134,7 @@ pub async fn list(
.select_only()
.column_as(project::Column::Id.count(), "count")
.into_tuple::<i64>()
.one(&state.db)
.one(db::conn())
.await
{
Err(err) => {
Expand All @@ -151,7 +149,7 @@ pub async fn list(
.order_by(project::Column::Id, Order::Desc)
.offset(offset)
.limit(limit)
.all(&state.db)
.all(db::conn())
.await
{
Err(err) => {
Expand Down Expand Up @@ -198,13 +196,12 @@ pub struct ProjAccount {
}

pub async fn detail(
State(state): State<AppState>,
Extension(identity): Extension<Identity>,
Path(project_id): Path<u64>,
) -> Result<ApiOK<RespDetail>> {
let (model_proj, model_account) = match Project::find_by_id(project_id)
.find_also_related(Account)
.one(&state.db)
.one(db::conn())
.await
{
Err(err) => {
Expand Down
Loading

0 comments on commit 10b0b95

Please sign in to comment.