Skip to main content

mycommon_utils/utils/
jwt_util.rs

1use serde::{Deserialize, Serialize};
2use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
3use jsonwebtoken::errors::ErrorKind;
4use serde::de::DeserializeOwned;
5use crate::database::BigIntPrimaryKey;
6use crate::error::Error;
7
8/// JWT 鉴权 Token结构
9#[derive(Debug, Serialize, Deserialize, Clone, Default)]
10pub struct JWTToken {
11    // 账号归属
12    pub store_id: BigIntPrimaryKey,
13    // 用户ID
14    pub user_id: BigIntPrimaryKey,
15    //token
16    pub token: String,
17    //过期时间
18    pub exp: usize,
19}
20
21
22impl AuthToken for JWTToken {}
23
24pub trait AuthToken: for<'de> Deserialize<'de> {
25    /// 创建 token
26    fn create_token(&self, secret: &str) -> Result<String, Error>
27    where
28        Self: Serialize,
29        Self: Sized,
30    {
31        return match encode(
32            &Header::default(),
33            self,
34            &EncodingKey::from_secret(secret.as_ref()),
35        ) {
36            Ok(t) => Ok(t),
37            Err(_) => Err(Error::from("JWTToken encode fail!")), // in practice you would return the error
38        };
39    }
40
41    /// 还原token
42    fn verify<T: DeserializeOwned>(secret: &str, token: &str) -> Result<T, Error> {
43        // let validation = Validation { ..Validation::default() };
44        return match decode::<T>(
45            &token,
46            &DecodingKey::from_secret(secret.as_ref()),
47            &Validation::default(),
48        ) {
49            Ok(c) => Ok(c.claims),
50            Err(err) => {
51                return match *err.kind() {
52                    ErrorKind::InvalidToken => Err(Error::from("InvalidToken")), // Example on how to handle a specific error
53                    ErrorKind::InvalidIssuer => Err(Error::from("InvalidIssuer")), // Example on how to handle a specific error
54                    _ => Err(Error::from("InvalidToken other errors")),
55                };
56            }
57        };
58    }
59}
60
61
62#[derive(Debug)]
63pub enum AuthError {
64    WrongCredentials,
65    MissingCredentials,
66    TokenCreation,
67    InvalidToken,
68    CheckOutToken,
69}
70
71
72#[derive(Debug, Serialize, Deserialize, Clone)]
73#[serde(rename_all = "camelCase")]
74pub struct AuthBody {
75    token: String,
76    token_type: String,
77    pub exp: usize,
78    exp_in: usize,
79    store_id: BigIntPrimaryKey,
80    dept_id: BigIntPrimaryKey,
81    personnel_number: String,
82    user_id: BigIntPrimaryKey,
83    user_name: String,
84    nick_name: String,
85    user_type: String,
86    gender: String,
87    phone_number: String,
88}
89impl AuthBody {
90    pub fn new(access_token: String, exp: usize, exp_in: usize,
91               store_id: BigIntPrimaryKey,
92               dept_id: BigIntPrimaryKey,
93               personnel_number: String,
94               user_id: BigIntPrimaryKey,
95               user_name: String,
96               nick_name: String,
97               user_type: String,
98               gender: String,
99               phone_number: String
100    ) -> Self {
101        Self {
102            token: access_token,
103            token_type: "Access-Token".to_string(),
104            exp,
105            exp_in,
106            store_id,
107            dept_id,
108            personnel_number,
109            user_id,
110            user_name,
111            nick_name,
112            user_type,
113            gender,
114            phone_number,
115        }
116    }
117}
118
119
120/// JWT 鉴权 Token结构
121#[derive(Debug, Serialize, Deserialize, Clone)]
122pub struct AppJWTToken {
123    //账号id
124    pub store_id: BigIntPrimaryKey,
125    //账号id
126    pub user_id: BigIntPrimaryKey,
127    //uuid
128    pub token: String,
129    //过期时间
130    pub exp: usize,
131}
132impl AuthToken for AppJWTToken {}