Skip to main content

g3_auth_macros/
lib.rs

1//! Proc macros for [g3-auth](https://docs.rs/g3-auth). Use them through
2//! `g3_auth::public` and `g3_auth::PublicRoutes`.
3
4use proc_macro::TokenStream;
5use proc_macro2::TokenStream as TokenStream2;
6
7mod public;
8mod routes;
9
10/// Marks a server function as reachable without a session.
11///
12/// g3-auth's auth guard denies every request that has no signed-in user,
13/// unless its path is a static asset, a public page the app names, or a
14/// server function marked with this attribute. Place it **above** the route
15/// attribute:
16///
17/// ```ignore
18/// #[g3_auth::public]
19/// #[get("/api/v1/is_signed_in", ctx: SessionContext)]
20/// pub async fn is_signed_in() -> Result<bool> { .. }
21/// ```
22///
23/// Forgetting it is the safe mistake: the endpoint answers a signed-out
24/// caller with `401`. Adding it is a deliberate, reviewable line next to the
25/// function it opens up, so say why in a comment.
26///
27/// # Checked at compile time
28///
29/// - It sits above a `#[get]`, `#[post]`, `#[put]`, `#[patch]` or `#[delete]`
30///   with an explicit path. Below it, the route attribute has already
31///   expanded; `#[server]` derives its path at build time.
32/// - The path starts with `/`. A `?query` suffix is ignored, and `{param}`
33///   segments match any one segment.
34///
35/// In a build without `g3-auth/server` it registers nothing, so client
36/// builds compile the same code.
37#[proc_macro_attribute]
38pub fn public(attr: TokenStream, item: TokenStream) -> TokenStream {
39    report(public::expand(attr.into(), item.clone().into()), item)
40}
41
42/// The expansion, or the item unchanged plus the error, so one mistake
43/// doesn't also bury the function under "cannot find" errors.
44fn report(result: syn::Result<TokenStream2>, item: TokenStream) -> TokenStream {
45    match result {
46        Ok(tokens) => tokens.into(),
47        Err(err) => {
48            let mut item: TokenStream2 = item.into();
49            item.extend(err.to_compile_error());
50            item.into()
51        }
52    }
53}
54
55/// Marks pages of a `Routable` enum as reachable without a session.
56///
57/// Derive it next to `Routable` and put `#[public]` on each page a signed-out
58/// visitor may load: the splash, sign-in, legal pages, share links.
59///
60/// ```ignore
61/// #[derive(Clone, Routable, PartialEq, PublicRoutes)]
62/// enum Route {
63///     #[redirect("/:..segments", |segments: Vec<String>| Route::Splash {})]
64///     #[public]
65///     #[route("/")]
66///     Splash {},
67///     #[nest("/games/:game_id")]
68///         #[public]
69///         #[route("/join")]
70///         JoinGame { game_id: String },
71///     #[end_nest]
72///     #[route("/home")]
73///     Home {},
74/// }
75///
76/// let guard = AuthGuard::for_routes(Route::Splash {});
77/// ```
78///
79/// It implements `g3_auth::PublicRoutes` from the variants' own
80/// `#[route]` and enclosing `#[nest]` paths, and matches a request path
81/// against those directly. It never parses the path into the enum: a
82/// catch-all `#[redirect]` would turn every unknown path, and every `/api/`
83/// path, into its target, and a check on the parsed value would open them
84/// all. Redirects are never public.
85///
86/// # Checked at compile time
87///
88/// - `#[public]` takes no arguments and sits on a variant with `#[route]`.
89/// - Not on a `#[child]` variant, whose paths live in another enum.
90/// - `#[nest]` and `#[end_nest]` pair up.
91#[proc_macro_derive(PublicRoutes, attributes(public))]
92pub fn derive_public_routes(item: TokenStream) -> TokenStream {
93    match routes::expand(item.into()) {
94        Ok(tokens) => tokens.into(),
95        Err(err) => err.to_compile_error().into(),
96    }
97}