Skip to content

Commit ee957b6

Browse files
Improve document (#1070)
* Improve document * Format Rust code using rustfmt * u * wip --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 09baa3f commit ee957b6

21 files changed

+415
-161
lines changed

crates/extra/src/affix_state.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
//! Middleware for add any data to depot.
1+
//! Middleware for adding shared application state to the request context.
2+
//!
3+
//! This middleware allows you to inject any data into the Depot, making it
4+
//! available to all subsequent handlers in the request pipeline. This is useful
5+
//! for sharing configuration, database connections, and other application state.
26
//!
37
//! # Example
48
//!
@@ -76,15 +80,19 @@ where
7680
}
7781
}
7882

79-
/// Inject a value into depot.
83+
/// Inject a typed value into depot using the type's ID as the key.
84+
///
85+
/// This is useful when you want to access the value by its type rather than by an explicit key.
8086
///
8187
/// View [module level documentation](index.html) for more details.
8288
#[inline]
8389
pub fn inject<V: Send + Sync + Clone + 'static>(value: V) -> AffixList {
8490
insert(format!("{:?}", TypeId::of::<V>()), value)
8591
}
8692

87-
/// Insert a key-value pair into depot.
93+
/// Insert a key-value pair into depot with an explicit key.
94+
///
95+
/// Use this when you need to access the value using a specific key string.
8896
///
8997
/// View [module level documentation](index.html) for more details.
9098
#[inline]

crates/extra/src/basic_auth.rs

+12-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
//! Middleware for basic authentication.
1+
//! Middleware for HTTP Basic Authentication.
2+
//!
3+
//! This middleware implements the standard HTTP Basic Authentication scheme as described in RFC 7617.
4+
//! It extracts credentials from the Authorization header and validates them against your custom validator.
25
//!
36
//! # Example
47
//!
@@ -35,14 +38,18 @@ use salvo_core::{async_trait, Depot, Error, FlowCtrl, Handler};
3538
/// key used when insert into depot.
3639
pub const USERNAME_KEY: &str = "::salvo::basic_auth::username";
3740

38-
/// BasicAuthValidator
41+
/// Validator for Basic Authentication credentials.
3942
pub trait BasicAuthValidator: Send + Sync {
40-
/// Validate is that username and password is right.
43+
/// Validates whether the provided username and password are correct.
44+
///
45+
/// Implement this method to check credentials against your authentication system.
46+
/// Return `true` if authentication succeeds, `false` otherwise.
4147
fn validate(&self, username: &str, password: &str, depot: &mut Depot) -> impl Future<Output = bool> + Send;
4248
}
43-
/// BasicAuthDepotExt
49+
50+
/// Extension trait for retrieving the authenticated username from a Depot.
4451
pub trait BasicAuthDepotExt {
45-
/// Get basic auth username reference.
52+
/// Returns the authenticated username if authentication was successful.
4653
fn basic_auth_username(&self) -> Option<&str>;
4754
}
4855

crates/extra/src/caching_headers.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
//! Middleware for etag and last-modified-since headers.
1+
//! Middleware for handling ETag and Last-Modified headers.
22
//!
33
//! This crate provides three handlers: [`ETag`], [`Modified`], and [`CachingHeaders`].
4-
//! Unless you are sure that you _don't_ want either etag or last-modified
5-
//! behavior, please use the combined [`CachingHeaders`] handler.
4+
//! Unless you are sure that you _don't_ want either ETag or Last-Modified
5+
//! behavior, use the combined [`CachingHeaders`] handler for better cache control.
66
77
use etag::EntityTag;
88
use salvo_core::http::header::{ETAG, IF_NONE_MATCH};
@@ -157,6 +157,10 @@ impl Handler for Modified {
157157
}
158158

159159
/// A combined handler that provides both [`ETag`] and [`Modified`] behavior.
160+
///
161+
/// This handler helps improve performance by preventing unnecessary data transfers
162+
/// when a client already has the latest version of a resource, as determined by
163+
/// either ETag or Last-Modified comparisons.
160164
#[derive(Clone, Debug, Copy, Default)]
161165
pub struct CachingHeaders(Modified, ETag);
162166

crates/extra/src/catch_panic.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ use salvo_core::http::{Request, Response, StatusError};
3030
use salvo_core::{async_trait, Depot, FlowCtrl, Error, Handler};
3131

3232

33-
/// Middleware for catch panic in handlers.
33+
/// Middleware that catches panics in handlers and converts them to HTTP 500 responses.
34+
///
35+
/// This middleware should be registered as the first middleware in your router chain
36+
/// to ensure it catches panics from all subsequent handlers and middlewares.
3437
///
3538
/// View [module level documentation](index.html) for more details.
3639
#[derive(Default, Debug)]

crates/extra/src/concurrency_limiter.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
//! Middleware for limit concurrency.
1+
//! Middleware for limiting concurrency.
22
//!
3-
//! Limit the max number of requests being concurrently processed.
3+
//! This middleware limits the maximum number of requests being processed concurrently,
4+
//! which helps prevent server overload during traffic spikes.
45
//!
5-
//! Example:
6+
//! # Example
67
//!
78
//! ```no_run
89
//! use std::fs::create_dir_all;

crates/flash/src/session_store.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use super::{Flash, FlashHandler, FlashStore};
77
#[derive(Debug)]
88
#[non_exhaustive]
99
pub struct SessionStore {
10-
/// The cookie name for the flash messages.
10+
/// The session key for the flash messages.
1111
pub name: String,
1212
}
1313
impl Default for SessionStore {
@@ -24,13 +24,13 @@ impl SessionStore {
2424
}
2525
}
2626

27-
/// Sets cookie name.
27+
/// Sets session key name.
2828
pub fn name(mut self, name: impl Into<String>) -> Self {
2929
self.name = name.into();
3030
self
3131
}
3232

33-
/// Into `FlashHandler`.
33+
/// Converts into `FlashHandler`.
3434
pub fn into_handler(self) -> FlashHandler<SessionStore> {
3535
FlashHandler::new(self)
3636
}
@@ -43,13 +43,13 @@ impl FlashStore for SessionStore {
4343
async fn save_flash(&self, _req: &mut Request, depot: &mut Depot, _res: &mut Response, flash: Flash) {
4444
if let Err(e) = depot
4545
.session_mut()
46-
.expect("session must be exist")
46+
.expect("session must exist")
4747
.insert(&self.name, flash)
4848
{
4949
tracing::error!(error = ?e, "save flash to session failed");
5050
}
5151
}
5252
async fn clear_flash(&self, depot: &mut Depot, _res: &mut Response) {
53-
depot.session_mut().expect("session must be exist").remove(&self.name);
53+
depot.session_mut().expect("session must exist").remove(&self.name);
5454
}
5555
}

crates/jwt-auth/README.md

+12-2
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,19 @@ Salvo is an extremely simple and powerful Rust web backend framework. Only basic
3737

3838
# salvo-jwt-auth
3939

40-
## Jwt auth middleware for Salvo.
40+
JWT (JSON Web Token) authentication middleware for the Salvo web framework.
4141

42-
This is an official crate, so you can enable it in `Cargo.toml` like this:
42+
## Features
43+
44+
- **Flexible token extraction**: Extract tokens from headers, query parameters, cookies, or form data
45+
- **Multiple authentication strategies**: Use either static keys or OpenID Connect for token validation
46+
- **Easy integration**: Works seamlessly within Salvo's middleware system
47+
- **Type-safe claims**: Decode tokens into your own custom claims structs
48+
- **Configurable validation**: Customize token validation rules
49+
50+
## Installation
51+
52+
This is an official crate, so you can enable it in `Cargo.toml`:
4353

4454
```toml
4555
salvo = { version = "*", features = ["jwt-auth"] }

crates/jwt-auth/src/decoder.rs

+41-10
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,33 @@ use serde::Deserialize;
44

55
use salvo_core::Depot;
66

7-
/// JwtAuthDecoder is used to decode a token into claims.
7+
/// Trait for JWT token decoding and validation.
8+
///
9+
/// Implementors of this trait are responsible for decoding JWT tokens into claims objects
10+
/// and performing any necessary validation. The `JwtAuth` middleware uses the configured
11+
/// decoder to validate tokens extracted from requests.
12+
///
13+
/// The crate provides built-in implementations:
14+
/// - `ConstDecoder`: Uses a static key for token validation
15+
/// - `OidcDecoder`: Uses OpenID Connect for validation (requires the `oidc` feature)
816
pub trait JwtAuthDecoder {
9-
/// Error type.
17+
/// The error type returned if decoding or validation fails.
1018
type Error: std::error::Error + Send + Sync + 'static;
1119

12-
///Decode token.
20+
/// Decodes and validates a JWT token.
21+
///
22+
/// # Parameters
23+
///
24+
/// * `token` - The JWT token string to decode
25+
/// * `depot` - The current request's depot, which can be used to store/retrieve additional data
26+
///
27+
/// # Type Parameters
28+
///
29+
/// * `C` - The claims type to deserialize from the token payload
30+
///
31+
/// # Returns
32+
///
33+
/// Returns a `Result` containing either the decoded token data or an error.
1334
fn decode<C>(
1435
&self,
1536
token: &str,
@@ -19,41 +40,51 @@ pub trait JwtAuthDecoder {
1940
C: for<'de> Deserialize<'de>;
2041
}
2142

22-
/// ConstDecoder will decode token with a static secret.
43+
/// A decoder that uses a constant key for JWT token validation.
44+
///
45+
/// This is the simplest decoder implementation, suitable for applications using
46+
/// symmetric key signing (HMAC) or a single asymmetric key pair (RSA, ECDSA).
2347
pub struct ConstDecoder {
48+
/// Key used for validating JWT signatures
2449
decoding_key: DecodingKey,
50+
51+
/// JWT validation parameters
2552
validation: Validation,
2653
}
2754

2855
impl ConstDecoder {
29-
/// Create a new `ConstDecoder`.
56+
/// Creates a new decoder with the given decoding key and default validation.
3057
pub fn new(decoding_key: DecodingKey) -> Self {
3158
Self {
3259
decoding_key,
3360
validation: Validation::default(),
3461
}
3562
}
36-
/// Create a new `ConstDecoder` with validation.
63+
64+
/// Creates a new decoder with the given decoding key and custom validation parameters.
3765
pub fn with_validation(decoding_key: DecodingKey, validation: Validation) -> Self {
3866
Self {
3967
decoding_key,
4068
validation,
4169
}
4270
}
4371

44-
/// If you're using HMAC, use this.
72+
/// Creates a decoder from a raw secret byte array for HMAC verification.
73+
///
74+
/// This is the most common method for symmetric key validation.
4575
pub fn from_secret(secret: &[u8]) -> Self {
4676
Self::with_validation(DecodingKey::from_secret(secret), Validation::default())
4777
}
4878

49-
/// If you're using HMAC with a base64 encoded secret, use this.
79+
/// Creates a decoder from a base64-encoded secret string for HMAC verification.
5080
pub fn from_base64_secret(secret: &str) -> Result<Self, JwtError> {
5181
DecodingKey::from_base64_secret(secret)
5282
.map(|key| Self::with_validation(key, Validation::default()))
5383
}
5484

55-
/// If you are loading a public RSA key in a PEM format, use this.
56-
/// Only exists if the feature `use_pem` is enabled.
85+
/// Creates a decoder from an RSA public key in PEM format.
86+
///
87+
/// Only available when the `use_pem` feature is enabled.
5788
pub fn from_rsa_pem(key: &[u8]) -> Result<Self, JwtError> {
5889
DecodingKey::from_rsa_pem(key)
5990
.map(|key| Self::with_validation(key, Validation::new(Algorithm::RS256)))

0 commit comments

Comments
 (0)