1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
extern crate proc_macro;
#[macro_use]
extern crate syn;
#[macro_use]
extern crate quote;

use self::proc_macro::TokenStream;
use syn::{
    fold::Fold,
    parse::{Parse, ParseStream, Result as ParseResult},
    punctuated::Punctuated,
    Block, FnDecl, ItemFn, LitStr,
};

/// Parses a list of string constants that represent user roles, separated by
/// commas.
struct Args {
    roles: Vec<String>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> ParseResult<Self> {
        let roles = Punctuated::<LitStr, Token![,]>::parse_terminated(input)?;
        Ok(Args {
            roles: roles.iter().map(|lit| lit.value()).collect(),
        })
    }
}

impl Fold for Args {
    /// Adds an additional argument to the function signature: `user_roles:
    /// UserRoles`.
    fn fold_fn_decl(&mut self, mut i: FnDecl) -> FnDecl {
        // Add a new argument to the function for user roles
        i.inputs.push(parse_quote!(user_roles: UserRoles));
        i
    }

    /// Wrap the function body in an if/else that verifies that the user has
    /// all of the roles required to use this endpoint. The incoming block
    /// is the function body.
    fn fold_block(&mut self, i: Block) -> Block {
        let roles = &self.roles; // The roles required by this endpoint

        // Builds an array of string literals, representing the roles to check.
        // Each of these literals will be checked against the incoming roles
        // each time a request is served.
        //
        // This assumes that the function has a param named `user_roles` of
        // type `UserRoles`, which it will because we add it ourselves.
        parse_quote!({
            if user_roles.has_roles(&[#(#roles),*]) {
                #i // The normal function body
            } else {
                Err(Status::Unauthorized.into()) // Get up on outta here
            }
        })
    }
}

/// Wraps a route function in a guard that only calls the function body if the
/// user has sufficient roles. This proc macro must come **before** the route
/// proc macro!
#[proc_macro_attribute]
pub fn auth(args: TokenStream, input: TokenStream) -> TokenStream {
    let mut args = parse_macro_input!(args as Args);
    let input = parse_macro_input!(input as ItemFn);
    let output = args.fold_item_fn(input);
    TokenStream::from(quote!(#output))
}