use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde_json::Value;
#[tauri::command]
pub fn verify_jwt(token: String, secret_or_pem: String) -> Result<bool, String> {
let header = decode_header(&token).map_err(|e| e.to_string())?;
let alg = header.alg;
let key = match alg {
Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
DecodingKey::from_secret(secret_or_pem.as_bytes())
}
Algorithm::RS256
| Algorithm::RS384
| Algorithm::RS512
| Algorithm::PS256
| Algorithm::PS384
| Algorithm::PS512 => {
DecodingKey::from_rsa_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
}
Algorithm::ES256 | Algorithm::ES384 => {
DecodingKey::from_ec_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
}
Algorithm::EdDSA => {
DecodingKey::from_ed_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
}
other => return Err(format!("Unsupported algorithm: {other:?}")),
};
let mut validation = Validation::new(alg);
validation.validate_exp = false;
validation.validate_nbf = false;
validation.required_spec_claims.clear();
match decode::<Value>(&token, &key, &validation) {
Ok(_) => Ok(true),
Err(e) => match e.kind() {
ErrorKind::InvalidSignature => Ok(false),
_ => Err(e.to_string()),
},
}
}