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;
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct JWTToken {
pub store_id: BigIntPrimaryKey,
pub user_id: BigIntPrimaryKey,
pub token: String,
pub exp: usize,
}
impl AuthToken for JWTToken {}
pub trait AuthToken: for<'de> Deserialize<'de> {
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!")), };
}
fn verify<T: DeserializeOwned>(secret: &str, token: &str) -> Result<T, Error> {
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")), ErrorKind::InvalidIssuer => Err(Error::from("InvalidIssuer")), _ => 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,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AppJWTToken {
pub store_id: BigIntPrimaryKey,
pub user_id: BigIntPrimaryKey,
pub token: String,
pub exp: usize,
}
impl AuthToken for AppJWTToken {}