diff options
Diffstat (limited to 'src/auth')
-rw-r--r-- | src/auth/claims.rs | 29 | ||||
-rw-r--r-- | src/auth/error.rs | 3 | ||||
-rw-r--r-- | src/auth/jwt.rs | 8 |
3 files changed, 15 insertions, 25 deletions
diff --git a/src/auth/claims.rs b/src/auth/claims.rs index 67c4fbb..652a47f 100644 --- a/src/auth/claims.rs +++ b/src/auth/claims.rs @@ -106,18 +106,10 @@ const ACCESS: i64 = 86400; pub type AccessClaims = Claims<ACCESS>; -impl From<RefreshClaims> for AccessClaims { - fn from(value: RefreshClaims) -> Self { - Claims::issue(value.sub) - } -} - -impl TryFrom<AccessClaims> for Cookie<'_> { - type Error = Error; - - fn try_from(value: AccessClaims) -> Result<Self, Self::Error> { - Ok(Cookie::build(("token", JWT.encode(&value)?)) - .expires(value.exp) +impl AccessClaims { + pub fn as_cookie(&self) -> Result<Cookie, Error> { + Ok(Cookie::build(("token", JWT.encode(&self)?)) + .expires(self.exp) .secure(true) .http_only(true) .path("/api") @@ -125,14 +117,9 @@ impl TryFrom<AccessClaims> for Cookie<'_> { } } -impl TryFrom<AccessClaims> for HeaderValue { - type Error = Error; - - fn try_from(value: AccessClaims) -> Result<Self, Self::Error> { - Cookie::try_from(value)? - .to_string() - .parse() - .map_err(Into::into) +impl From<RefreshClaims> for AccessClaims { + fn from(value: RefreshClaims) -> Self { + Claims::issue(value.sub) } } @@ -150,7 +137,7 @@ impl IntoResponseParts for AccessClaims { mut res: axum::response::ResponseParts, ) -> Result<axum::response::ResponseParts, Self::Error> { res.headers_mut() - .append(SET_COOKIE, HeaderValue::try_from(self)?); + .try_append(SET_COOKIE, self.as_cookie()?.to_string().parse()?)?; Ok(res) } diff --git a/src/auth/error.rs b/src/auth/error.rs index 3a111ca..91aec5c 100644 --- a/src/auth/error.rs +++ b/src/auth/error.rs @@ -9,6 +9,9 @@ pub enum Error { #[error("Failed to parse header: {0} (wrong token type?)")] HeaderRejection(axum_extra::typed_header::TypedHeaderRejection), + #[error("Failed to append header: {0}")] + HeaderMaxSizeReached(#[from] axum::http::header::MaxSizeReached), + #[error("Database error: {0}")] Sqlx(#[from] sqlx::Error), diff --git a/src/auth/jwt.rs b/src/auth/jwt.rs index 0d7b593..f44b7d4 100644 --- a/src/auth/jwt.rs +++ b/src/auth/jwt.rs @@ -4,19 +4,19 @@ use serde::{de::DeserializeOwned, Serialize}; use super::Error; -pub static JWT: Lazy<Jwt> = Lazy::new(|| { +pub static JWT: Lazy<JwtTranscoder> = Lazy::new(|| { let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"); - Jwt::new(secret.as_bytes()) + JwtTranscoder::new(secret.as_bytes()) }); -pub struct Jwt { +pub struct JwtTranscoder { encoding: EncodingKey, decoding: DecodingKey, header: jsonwebtoken::Header, validation: jsonwebtoken::Validation, } -impl Jwt { +impl JwtTranscoder { fn new(secret: &[u8]) -> Self { Self { encoding: EncodingKey::from_secret(secret), |