protect_axum/lib.rs
1#![doc(
2 html_logo_url = "https://raw.githubusercontent.com/DDtKey/protect-endpoints/main/protect-axum/logo.png"
3)]
4//! A crate to protect your endpoints in [`axum`].
5//!
6//! For built-in configuration, you can use [`GrantsLayer`] tower compatible middleware.
7//!
8//! To check user access to specific services, you can use [`proc-macro`] or manual.
9//!
10//! [`permissions`]: authorities
11//! [`proc-macro`]: proc_macro
12//! [`axum`]: https://github.com/tokio-rs/axum
13#![doc = include_str!("../README.md")]
14
15use protect_endpoints_core::tower::middleware::GrantsLayer as CoreGrantsLayer;
16
17pub mod authorities;
18
19pub type GrantsLayer<Extractor, Type, Err> =
20 CoreGrantsLayer<Extractor, axum::extract::Request, Type, Err>;
21
22/// Procedural macros for checking user authorities (permissions or roles).
23///
24/// # Examples
25/// ```
26/// use axum::{http::StatusCode, Extension};
27/// use axum::extract::Path;
28///
29/// // User should be ADMIN with OP_GET_SECRET permission
30/// #[protect_axum::protect("ROLE_ADMIN", "OP_GET_SECRET")]
31/// async fn macro_secured() -> (StatusCode, &'static str) {
32/// (StatusCode::OK, "some secured info")
33/// }
34///
35/// // User should be ADMIN and MANAGER
36/// #[protect_axum::protect("ADMIN", "MANAGER")]
37/// async fn role_macro_secured() -> (StatusCode, &'static str) {
38/// (StatusCode::OK, "some secured info")
39/// }
40///
41/// // Additional security condition to ensure the protection of the endpoint
42/// #[protect_axum::protect("USER", expr = "*user_id == user.id")]
43/// async fn role_macro_secured_with_params(user_id: Path<i32>, user: Extension<&User>) -> (StatusCode, &'static str) {
44/// (StatusCode::OK, "some secured info with parameters")
45/// }
46/// struct User { id: i32 }
47///
48/// // You own type is also supported (need to configure middleware for this type as well):
49/// #[protect_axum::protect("Role::Admin", "Role::Manager", ty = "Role")]
50/// async fn role_enum_macro_secured() -> (StatusCode, &'static str) {
51/// (StatusCode::OK, "some secured info")
52/// }
53/// #[derive(Eq, PartialEq, Hash)] // required bounds
54/// enum Role { Admin, Manager }
55///
56/// ```
57#[cfg(feature = "macro-check")]
58pub mod proc_macro {
59 pub use protect_endpoints_proc_macro::protect_axum as protect;
60}
61
62/// Just a shortcut for proc-macros
63#[cfg(feature = "macro-check")]
64pub use proc_macro::*;