mycommon-utils 0.2.1

Common utilities library for database operations, Redis caching and system utilities
Documentation
use serde::{Deserialize, Serialize};
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use jsonwebtoken::errors::ErrorKind;
use serde::de::DeserializeOwned;
use crate::database::BigIntPrimaryKey;
use crate::error::Error;

/// JWT 鉴权 Token结构
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct JWTToken {
    // 账号归属
    pub store_id: BigIntPrimaryKey,
    // 用户ID
    pub user_id: BigIntPrimaryKey,
    //token
    pub token: String,
    //过期时间
    pub exp: usize,
}


impl AuthToken for JWTToken {}

pub trait AuthToken: for<'de> Deserialize<'de> {
    /// 创建 token
    fn create_token(&self, secret: &str) -> Result<String, Error>
    where
        Self: Serialize,
        Self: Sized,
    {
        return match encode(
            &Header::default(),
            self,
            &EncodingKey::from_secret(secret.as_ref()),
        ) {
            Ok(t) => Ok(t),
            Err(_) => Err(Error::from("JWTToken encode fail!")), // in practice you would return the error
        };
    }

    /// 还原token
    fn verify<T: DeserializeOwned>(secret: &str, token: &str) -> Result<T, Error> {
        // let validation = Validation { ..Validation::default() };
        return match decode::<T>(
            &token,
            &DecodingKey::from_secret(secret.as_ref()),
            &Validation::default(),
        ) {
            Ok(c) => Ok(c.claims),
            Err(err) => {
                return match *err.kind() {
                    ErrorKind::InvalidToken => Err(Error::from("InvalidToken")), // Example on how to handle a specific error
                    ErrorKind::InvalidIssuer => Err(Error::from("InvalidIssuer")), // Example on how to handle a specific error
                    _ => Err(Error::from("InvalidToken other errors")),
                };
            }
        };
    }
}


#[derive(Debug)]
pub enum AuthError {
    WrongCredentials,
    MissingCredentials,
    TokenCreation,
    InvalidToken,
    CheckOutToken,
}


#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AuthBody {
    token: String,
    token_type: String,
    pub exp: usize,
    exp_in: usize,
    store_id: BigIntPrimaryKey,
    dept_id: BigIntPrimaryKey,
    personnel_number: String,
    user_id: BigIntPrimaryKey,
    user_name: String,
    nick_name: String,
    user_type: String,
    gender: String,
    phone_number: String,
}
impl AuthBody {
    pub fn new(access_token: String, exp: usize, exp_in: usize,
               store_id: BigIntPrimaryKey,
               dept_id: BigIntPrimaryKey,
               personnel_number: String,
               user_id: BigIntPrimaryKey,
               user_name: String,
               nick_name: String,
               user_type: String,
               gender: String,
               phone_number: String
    ) -> Self {
        Self {
            token: access_token,
            token_type: "Access-Token".to_string(),
            exp,
            exp_in,
            store_id,
            dept_id,
            personnel_number,
            user_id,
            user_name,
            nick_name,
            user_type,
            gender,
            phone_number,
        }
    }
}


/// JWT 鉴权 Token结构
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppJWTToken {
    //账号id
    pub store_id: BigIntPrimaryKey,
    //账号id
    pub user_id: BigIntPrimaryKey,
    //uuid
    pub token: String,
    //过期时间
    pub exp: usize,
}
impl AuthToken for AppJWTToken {}