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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use proc_macro::{Span, TokenStream};
use quote::{format_ident, quote};
use std::collections::HashMap;
use syn::{
parse_macro_input, AttributeArgs, DeriveInput, Expr, ExprLit, ExprPath, Lit, LitStr, Meta,
NestedMeta,
};
const ONE_MONTH_IN_SECONDS: u64 = 2592_000;
const ONE_MINUTE_IN_SECONDS: u64 = 60;
fn get_lit_int(lit: Option<&Lit>, default_value: u64) -> u64 {
match lit {
Some(exp_lit) => {
if let Lit::Int(exp_lit_int) = exp_lit {
exp_lit_int.base10_digits().parse::<u64>().unwrap()
} else {
default_value
}
}
None => default_value,
}
}
fn parse_invocation(attr: Vec<NestedMeta>, input: DeriveInput) -> TokenStream {
let mut attr_into_iter = attr.into_iter();
let secret = attr_into_iter.next();
let mut secrete_value: Expr = Expr::Lit(ExprLit {
attrs: Vec::new(),
lit: Lit::Str(LitStr::new("", Span::call_site().into())),
});
if let Some(secret) = secret {
match secret {
NestedMeta::Lit(lit) => {
if let Lit::Str(lit_str) = lit {
secrete_value = Expr::Lit(ExprLit {
attrs: Vec::new(),
lit: Lit::Str(lit_str),
});
}
}
NestedMeta::Meta(meta) => {
if let Meta::Path(secret_path) = meta {
secrete_value = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: secret_path,
})
}
}
}
}
let mut hashmap: HashMap<String, Lit> = HashMap::new();
for attr_iter in attr_into_iter.into_iter() {
if let NestedMeta::Meta(meta) = attr_iter {
if let Meta::NameValue(namevalue) = meta {
let name = namevalue.path;
let value = namevalue.lit;
let name = name.segments[0].ident.to_string();
hashmap.insert(name, value);
}
}
}
let exp = get_lit_int(hashmap.get("exp"), ONE_MONTH_IN_SECONDS);
let leeway = get_lit_int(hashmap.get("leeway"), ONE_MINUTE_IN_SECONDS);
let guard_type = &input.ident;
let vis = &input.vis;
let fairing_name = format!("'{}' JwtFairing", "Test");
let guard_claim = format_ident!("{}JwtClaim", &guard_type);
let jwt = quote!(::jsonwebtoken);
#[allow(non_snake_case)]
let Result = quote!(::jsonwebtoken::errors::Result);
#[allow(non_snake_case)]
let Status = quote!(::rocket::http::Status);
#[allow(non_snake_case)]
let Outcome = quote!(::rocket::outcome::Outcome);
let request = quote!(::rocket::request);
let response = quote!(::rocket::response);
let std_time = quote!(::std::time);
let serder = quote!(::serde);
let guard_types = quote! {
#[derive(Debug, #serder::Deserialize, #serder::Serialize)]
#input
#[derive(Debug, #serder::Deserialize,#serder::Serialize)]
#vis struct #guard_claim {
exp: u64,
iat: u64,
user: #guard_type
}
};
quote! {
#guard_types
impl #guard_type {
pub fn fairing() -> impl ::rocket::fairing::Fairing {
::rocket::fairing::AdHoc::on_attach(#fairing_name, |rocket| {
Ok(rocket)
})
}
pub fn sign(user: #guard_type) -> String {
let now = #std_time::SystemTime::now().duration_since(#std_time::UNIX_EPOCH).unwrap().as_secs();
let payload = #guard_claim {
exp: #exp + now,
iat: now,
user,
};
#jwt::encode(&#jwt::Header::default(), &payload, &#jwt::EncodingKey::from_secret((#secrete_value).as_bytes())).unwrap()
}
pub fn decode(token: String) -> #Result<#guard_claim> {
let mut validation = #jwt::Validation::default();
validation.leeway = #leeway;
let result = #jwt::decode::<#guard_claim>(&token, &#jwt::DecodingKey::from_secret((#secrete_value).as_bytes()), &validation);
match result {
Ok(token_claim) => Ok(token_claim.claims),
Err(err) => Err(err),
}
}
}
impl<'a, 'r> #request::FromRequest<'a, 'r> for #guard_type {
type Error = #response::status::Custom<String>;
fn from_request(request: &'a #request::Request<'r>,) -> #request::Outcome<Self, #response::status::Custom<String>> {
if let Some(auth_header) = request.headers().get_one("Authorization") {
let auth_str = auth_header.to_string();
if auth_str.starts_with("Bearer") {
let token = auth_str[6..auth_str.len()].trim();
match #guard_type::decode(token.to_string()) {
Ok(token_data) => {
return #Outcome::Success(token_data.user);
},
Err(err) => {
return #Outcome::Failure((
#Status::Unauthorized,
#response::status::Custom(
#Status::Unauthorized,
err.to_string(),
),
));
},
}
}
}
#Outcome::Failure((
#Status::Unauthorized,
#response::status::Custom(
#Status::Unauthorized,
String::from("EmptySignature"),
),
))
}
}
}.into()
}
#[proc_macro_attribute]
pub fn jwt(attr: TokenStream, input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let attr = parse_macro_input!(attr as AttributeArgs);
parse_invocation(attr, input)
}