Skip to content

Commit a6aa7b6

Browse files
committed
feat: add docs
1 parent aff7eab commit a6aa7b6

3 files changed

Lines changed: 131 additions & 49 deletions

File tree

src/extractors/cookie.rs

Lines changed: 0 additions & 49 deletions
This file was deleted.

src/extractors/cookie_jar.rs

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/// This module provides functionality for extracting and managing cookies in HTTP requests.
2+
/// It includes a `CookieJar` struct that wraps the `cookie` crate's `CookieJar`
3+
/// and integrates with the application's request lifecycle.
4+
use anyhow::Result;
5+
use cookie::{Cookie, CookieJar as RawJar};
6+
use http::{HeaderMap, header::COOKIE};
7+
8+
use crate::{extractors::FromRequest, types::Request};
9+
10+
/// A wrapper around the `cookie::CookieJar` that provides methods for managing cookies
11+
/// in HTTP requests and responses.
12+
///
13+
/// This struct allows adding, removing, and retrieving cookies, as well as creating
14+
/// a `CookieJar` instance from HTTP headers.
15+
pub struct CookieJar(RawJar);
16+
17+
impl CookieJar {
18+
/// Creates a new, empty `CookieJar` instance.
19+
///
20+
/// # Returns
21+
/// A new `CookieJar` with no cookies.
22+
pub fn new() -> Self {
23+
Self(RawJar::new())
24+
}
25+
26+
/// Creates a `CookieJar` instance from the `Cookie` header in the provided HTTP headers.
27+
///
28+
/// # Parameters
29+
/// - `headers`: A reference to the HTTP headers containing the `Cookie` header.
30+
///
31+
/// # Returns
32+
/// A `CookieJar` populated with cookies parsed from the `Cookie` header.
33+
pub fn from_headers(headers: &HeaderMap) -> Self {
34+
let mut jar = RawJar::new();
35+
36+
if let Some(val) = headers.get(COOKIE).and_then(|v| v.to_str().ok()) {
37+
for s in val.split(';') {
38+
if let Ok(c) = Cookie::parse(s.trim()) {
39+
jar.add_original(c.into_owned());
40+
}
41+
}
42+
}
43+
44+
Self(jar)
45+
}
46+
47+
/// Adds a cookie to the `CookieJar`.
48+
///
49+
/// # Parameters
50+
/// - `cookie`: The cookie to add.
51+
pub fn add(&mut self, cookie: Cookie<'static>) {
52+
self.0.add(cookie);
53+
}
54+
55+
/// Removes a cookie from the `CookieJar` by its name.
56+
///
57+
/// # Parameters
58+
/// - `name`: The name of the cookie to remove.
59+
pub fn remove(&mut self, name: &str) {
60+
self.0.remove(Cookie::from(name.to_owned()));
61+
}
62+
63+
/// Retrieves a cookie from the `CookieJar` by its name.
64+
///
65+
/// # Parameters
66+
/// - `name`: The name of the cookie to retrieve.
67+
///
68+
/// # Returns
69+
/// An `Option` containing a reference to the cookie if it exists, or `None` otherwise.
70+
pub fn get(&self, name: &str) -> Option<&Cookie<'_>> {
71+
self.0.get(name)
72+
}
73+
74+
/// Returns an iterator over all cookies in the `CookieJar`.
75+
///
76+
/// # Returns
77+
/// An iterator yielding references to the cookies.
78+
pub fn iter(&self) -> impl Iterator<Item = &Cookie<'static>> {
79+
self.0.iter()
80+
}
81+
}
82+
83+
impl<'a> FromRequest<'a> for CookieJar {
84+
/// Extracts a `CookieJar` from an HTTP request.
85+
///
86+
/// This implementation reads the `Cookie` header from the request and populates
87+
/// the `CookieJar` with the parsed cookies.
88+
///
89+
/// # Parameters
90+
/// - `req`: A reference to the HTTP request.
91+
///
92+
/// # Returns
93+
/// A `Result` containing the `CookieJar` if successful.
94+
fn from_request(req: &'a Request) -> Result<Self> {
95+
Ok(CookieJar::from_headers(req.headers()))
96+
}
97+
}

src/middleware/jwt_auth.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/// This module provides middleware for handling JWT authentication in a web application.
2+
/// It supports multiple algorithms for verifying JWTs and integrates with the application's request/response lifecycle.
13
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
24

35
use http::{StatusCode, header::AUTHORIZATION};
@@ -10,6 +12,8 @@ use crate::{
1012
types::{Request, Response},
1113
};
1214

15+
/// Represents a verification key for various JWT algorithms.
16+
/// This enum supports multiple algorithms, including HMAC, RSA, and EdDSA.
1317
pub enum AnyVerifyKey {
1418
HS256(Arc<HS256Key>),
1519
HS384(Arc<HS384Key>),
@@ -32,6 +36,10 @@ pub enum AnyVerifyKey {
3236
}
3337

3438
impl AnyVerifyKey {
39+
/// Returns the algorithm identifier for the verification key.
40+
///
41+
/// # Returns
42+
/// A static string representing the algorithm (e.g., "HS256", "RS256").
3543
pub fn alg_id(&self) -> &'static str {
3644
match self {
3745
Self::HS256(_) => "HS256",
@@ -55,6 +63,13 @@ impl AnyVerifyKey {
5563
}
5664
}
5765

66+
/// Verifies a JWT token using the current verification key.
67+
///
68+
/// # Parameters
69+
/// - `token`: The JWT token to verify.
70+
///
71+
/// # Returns
72+
/// A `Result` containing the decoded claims if verification succeeds, or an error otherwise.
5873
pub fn verify<C>(&self, token: &str) -> Result<JWTClaims<C>, jwt_simple::Error>
5974
where
6075
C: Serialize + DeserializeOwned,
@@ -83,6 +98,10 @@ impl AnyVerifyKey {
8398
}
8499
}
85100

101+
/// Middleware for handling JWT authentication.
102+
///
103+
/// This struct allows configuring multiple verification keys for different algorithms
104+
/// and integrates with the application's middleware chain.
86105
pub struct JwtAuth<T>
87106
where
88107
T: DeserializeOwned + Send + Sync + 'static,
@@ -95,6 +114,14 @@ impl<T> JwtAuth<T>
95114
where
96115
T: DeserializeOwned + Send + Sync + 'static,
97116
{
117+
/// Creates a new instance of `JwtAuth` with the provided verification keys.
118+
///
119+
/// # Parameters
120+
/// - `keys`: A `HashMap` where the key is the algorithm identifier (e.g., "HS256")
121+
/// and the value is the corresponding verification key.
122+
///
123+
/// # Returns
124+
/// A new `JwtAuth` instance.
98125
pub fn new(keys: HashMap<&'static str, AnyVerifyKey>) -> Self {
99126
Self {
100127
keys: Arc::new(keys),
@@ -107,6 +134,13 @@ impl<T> IntoMiddleware for JwtAuth<T>
107134
where
108135
T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
109136
{
137+
/// Converts the `JwtAuth` instance into a middleware function.
138+
///
139+
/// The middleware extracts the JWT token from the `Authorization` header,
140+
/// verifies it using the configured keys, and injects the claims into the request's extensions.
141+
///
142+
/// # Returns
143+
/// A closure that represents the middleware function.
110144
fn into_middleware(
111145
self,
112146
) -> impl Fn(Request, Next) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>>

0 commit comments

Comments
 (0)