cool_core/middleware/
mod.rs1mod authority;
6mod exception;
7mod log;
8
9pub use authority::*;
10pub use exception::*;
11pub use log::*;
12
13use crate::error::CoolError;
14use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
15use salvo::prelude::*;
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct JwtClaims {
21 pub user_id: i64,
23 pub username: Option<String>,
25 pub role_ids: Vec<i64>,
27 pub is_admin: bool,
29 pub tenant_id: Option<i64>,
31 pub exp: i64,
33 pub iat: i64,
35}
36
37impl JwtClaims {
38 pub fn new(
40 user_id: i64,
41 username: Option<String>,
42 role_ids: Vec<i64>,
43 is_admin: bool,
44 tenant_id: Option<i64>,
45 expire_secs: u64,
46 ) -> Self {
47 let now = chrono::Utc::now().timestamp();
48 Self {
49 user_id,
50 username,
51 role_ids,
52 is_admin,
53 tenant_id,
54 exp: now + expire_secs as i64,
55 iat: now,
56 }
57 }
58
59 pub fn generate_token(&self, secret: &str) -> Result<String, CoolError> {
61 encode(
62 &Header::default(),
63 &self,
64 &EncodingKey::from_secret(secret.as_bytes()),
65 )
66 .map_err(CoolError::from)
67 }
68
69 pub fn verify_token(token: &str, secret: &str) -> Result<Self, CoolError> {
71 let token_data = decode::<Self>(
72 token,
73 &DecodingKey::from_secret(secret.as_bytes()),
74 &Validation::default(),
75 )
76 .map_err(CoolError::from)?;
77
78 Ok(token_data.claims)
79 }
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct AdminInfo {
85 pub user_id: i64,
87 pub username: Option<String>,
89 pub role_ids: Vec<i64>,
91 pub is_admin: bool,
93 pub tenant_id: Option<i64>,
95}
96
97impl From<JwtClaims> for AdminInfo {
98 fn from(claims: JwtClaims) -> Self {
99 Self {
100 user_id: claims.user_id,
101 username: claims.username,
102 role_ids: claims.role_ids,
103 is_admin: claims.is_admin,
104 tenant_id: claims.tenant_id,
105 }
106 }
107}
108
109pub trait DepotExt {
111 fn admin(&self) -> Option<&AdminInfo>;
112 fn set_admin(&mut self, admin: AdminInfo);
113}
114
115impl DepotExt for Depot {
116 fn admin(&self) -> Option<&AdminInfo> {
117 self.get::<AdminInfo>("admin").ok()
118 }
119
120 fn set_admin(&mut self, admin: AdminInfo) {
121 self.insert("admin", admin);
122 }
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct AppUserInfo {
128 pub id: i64,
130 pub username: Option<String>,
132 pub phone: Option<String>,
134 pub tenant_id: Option<i64>,
136}
137
138pub trait DepotAppUserExt {
140 fn app_user(&self) -> Option<&AppUserInfo>;
141 fn set_app_user(&mut self, user: AppUserInfo);
142}
143
144impl DepotAppUserExt for Depot {
145 fn app_user(&self) -> Option<&AppUserInfo> {
146 self.get::<AppUserInfo>("app_user").ok()
147 }
148
149 fn set_app_user(&mut self, user: AppUserInfo) {
150 self.insert("app_user", user);
151 }
152}