fastauth_macros/lib.rs
1//! Derive macros for [fastauth](https://github.com/lassejlv/fastauth). Use them through
2//! `fastauth` or `fastauth_core` (feature `macros`), which re-export each derive next to the
3//! trait it implements.
4//!
5//! The generated code names `fastauth_core` when the crate depends on it directly, and
6//! `fastauth::__private::core` when it only depends on the `fastauth` facade.
7
8use proc_macro::TokenStream;
9use proc_macro_crate::{FoundCrate, crate_name};
10use proc_macro2::TokenStream as TokenStream2;
11use quote::{format_ident, quote};
12use syn::{DeriveInput, parse_macro_input};
13
14mod auth_error;
15mod column;
16
17/// Implements `Fields` and `OnTable` for a struct of columns added to an existing table,
18/// plus a typed `Col` constant per field (`two_factor_enabled` becomes
19/// `TWO_FACTOR_ENABLED`).
20///
21/// ```
22/// use fastauth_core::plugin_prelude::*;
23///
24/// #[derive(Fields, Clone)]
25/// #[fields(table = User)]
26/// pub struct TwoFactorUser {
27/// #[field(default = false)]
28/// pub two_factor_enabled: bool,
29/// }
30///
31/// let _: Where<User> = TwoFactorUser::TWO_FACTOR_ENABLED.eq(true);
32/// ```
33///
34/// `#[fields(table = ..)]` names the model the columns live on, `User` when omitted.
35/// Field attributes, all inside `#[field(..)]`:
36///
37/// - `default = ..`: a bool, integer or string literal, or `now` for timestamps.
38/// - `input`: sign-up and update-user bodies may set it. Without it, clients never can.
39/// `input = false` spells out the default.
40/// - `returned = false`: never serialized to clients.
41/// - `unique`, `index`.
42/// - `rename = ".."`: the column name, when it differs from the field name.
43///
44/// `Option<T>` fields are nullable; the column type is `<T as ColumnValue>::TYPE`.
45#[proc_macro_derive(Fields, attributes(fields, field))]
46pub fn derive_fields(input: TokenStream) -> TokenStream {
47 let input = parse_macro_input!(input as DeriveInput);
48 column::derive_fields(&input, &core_path())
49 .unwrap_or_else(syn::Error::into_compile_error)
50 .into()
51}
52
53/// Implements `Model` and `OnTable<Table = Self>` for a table, plus a typed `Col` constant
54/// per field.
55///
56/// ```
57/// use fastauth_core::plugin_prelude::*;
58///
59/// #[derive(Model, Clone)]
60/// #[model(table = "api_key")]
61/// pub struct ApiKey {
62/// #[model(id)]
63/// pub id: Id,
64/// #[model(references = User, on_delete = Cascade, index)]
65/// pub user_id: Id,
66/// #[model(unique, hidden)]
67/// pub key_hash: Hash,
68/// #[model(default = now)]
69/// pub created_at: OffsetDateTime,
70/// }
71///
72/// let _: Where<ApiKey> = ApiKey::KEY_HASH.eq(Hash::sha256("ak_123"));
73/// ```
74///
75/// `#[model(table = "..")]` is required. Field attributes, all inside `#[model(..)]`:
76///
77/// - `id`: the primary key.
78/// - `references = Model`: a foreign key to that model's `id` column, with
79/// `on_delete = Cascade | SetNull | Restrict` (default `Restrict`).
80/// - `unique`, `index`, `hidden` (never serialized to clients).
81/// - `default = ..`: as for `Fields`.
82///
83/// Every field is a column; `created_at` and `updated_at` are not added for you. Encoding
84/// clones each field, so field types must be `Clone`.
85#[proc_macro_derive(Model, attributes(model))]
86pub fn derive_model(input: TokenStream) -> TokenStream {
87 let input = parse_macro_input!(input as DeriveInput);
88 column::derive_model(&input, &core_path())
89 .unwrap_or_else(syn::Error::into_compile_error)
90 .into()
91}
92
93/// Implements `From<E> for AuthError` and `ErrorCodes` for an enum of plugin errors.
94///
95/// ```
96/// use fastauth_core::plugin_prelude::*;
97///
98/// #[derive(AuthError, Debug)]
99/// #[auth_error(prefix = "API_KEY")]
100/// pub enum ApiKeyError {
101/// #[auth_error(status = 404, message = "API key not found")]
102/// NotFound,
103/// #[auth_error(status = 403, message = "scope {scope} is not allowed")]
104/// ScopeDenied { scope: String },
105/// }
106///
107/// let err = AuthError::from(ApiKeyError::ScopeDenied { scope: "admin".into() });
108/// assert_eq!(err.code(), "API_KEY_SCOPE_DENIED");
109/// assert_eq!(err.message(), "scope admin is not allowed");
110/// ```
111///
112/// Each variant's code is the prefix and the variant name in `SCREAMING_SNAKE_CASE`
113/// (`API_KEY_NOT_FOUND`); without a prefix it is the variant name alone. Messages can name
114/// fields of struct-like variants in `{field}` placeholders, formatted with `Display`.
115#[proc_macro_derive(AuthError, attributes(auth_error))]
116pub fn derive_auth_error(input: TokenStream) -> TokenStream {
117 let input = parse_macro_input!(input as DeriveInput);
118 auth_error::derive(&input, &core_path())
119 .unwrap_or_else(syn::Error::into_compile_error)
120 .into()
121}
122
123fn core_path() -> TokenStream2 {
124 let found = |name: &str| match crate_name(name).ok()? {
125 FoundCrate::Itself => Some(format_ident!("{}", name.replace('-', "_"))),
126 FoundCrate::Name(name) => Some(format_ident!("{name}")),
127 };
128 if let Some(core) = found("fastauth-core") {
129 return quote!(::#core);
130 }
131 if let Some(facade) = found("fastauth") {
132 return quote!(::#facade::__private::core);
133 }
134 quote!(::fastauth_core)
135}