use crate::error::JwkError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Jwk {
pub kty: String,
#[serde(rename = "use", skip_serializing_if = "Option::is_none")]
pub use_: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alg: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub n: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub e: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub crv: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub x: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub y: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub d: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Jwks {
pub keys: Vec<Jwk>,
}
pub struct JwkBuilder {
kty: String,
use_: Option<String>,
alg: Option<String>,
kid: Option<String>,
n: Option<String>,
e: Option<String>,
crv: Option<String>,
x: Option<String>,
y: Option<String>,
d: Option<String>,
}
impl JwkBuilder {
pub fn new(kty: &str) -> Self {
Self {
kty: kty.to_string(),
use_: None,
alg: None,
kid: None,
n: None,
e: None,
crv: None,
x: None,
y: None,
d: None,
}
}
pub fn set_key_use(&mut self, value: &str) -> &mut Self {
self.use_ = Some(value.to_string());
self
}
pub fn set_algorithm(&mut self, value: &str) -> &mut Self {
self.alg = Some(value.to_string());
self
}
pub fn set_key_id(&mut self, value: &str) -> &mut Self {
self.kid = Some(value.to_string());
self
}
pub fn set_modulus(&mut self, value: &str) -> &mut Self {
self.n = Some(value.to_string());
self
}
pub fn set_exponent(&mut self, value: &str) -> &mut Self {
self.e = Some(value.to_string());
self
}
pub fn set_curve_type(&mut self, value: &str) -> &mut Self {
self.crv = Some(value.to_string());
self
}
pub fn set_x_coordinate(&mut self, value: &str) -> &mut Self {
self.x = Some(value.to_string());
self
}
pub fn set_y_coordinate(&mut self, value: &str) -> &mut Self {
self.y = Some(value.to_string());
self
}
pub fn set_private_key(&mut self, value: &str) -> &mut Self {
self.d = Some(value.to_string());
self
}
pub fn build(&self) -> Result<Jwk, JwkError> {
match self.kty.as_str() {
"RSA" => {
if self.n.is_none() || self.e.is_none() {
return Err(JwkError::MissingRsaParams);
}
}
"EC" => {
if self.crv.is_none() || self.x.is_none() || self.y.is_none() {
return Err(JwkError::MissingEcParams);
}
}
_ => return Err(JwkError::UnsupportedKeyType(self.kty.clone())),
}
Ok(Jwk {
kty: self.kty.clone(),
use_: self.use_.clone(),
alg: self.alg.clone(),
kid: self.kid.clone(),
n: self.n.clone(),
e: self.e.clone(),
crv: self.crv.clone(),
x: self.x.clone(),
y: self.y.clone(),
d: self.d.clone(),
})
}
}
pub fn create_jwks(keys: Vec<Jwk>) -> Jwks {
Jwks { keys }
}