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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
extern crate iron;
extern crate urlencoded;
use super::code_grant::prelude::*;
use super::code_grant::{Authorizer, Issuer, Registrar};
use super::code_grant::frontend::{AccessFlow, AuthorizationFlow, GrantFlow, OwnerAuthorizer, WebRequest, WebResponse};
pub use super::code_grant::frontend::{AuthenticationRequest, Authentication, OAuthError};
pub use super::code_grant::Scope;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, LockResult, MutexGuard};
use std::ops::DerefMut;
use std::marker::PhantomData;
use self::iron::prelude::*;
use self::iron::headers::{Authorization as AuthHeader};
use self::iron::modifiers::Redirect;
use self::urlencoded::{UrlEncodedBody, UrlEncodedQuery};
use url::Url;
pub struct IronGranter<R, A, I> where
R: Registrar + Send + 'static,
A: Authorizer + Send + 'static,
I: Issuer + Send + 'static
{
registrar: Arc<Mutex<R>>,
authorizer: Arc<Mutex<A>>,
issuer: Arc<Mutex<I>>,
}
pub struct IronAuthorizer<PH, R, A> where
PH: GenericOwnerAuthorizer + Send + Sync,
R: Registrar + Send + 'static,
A: Authorizer + Send + 'static,
{
page_handler: Box<PH>,
registrar: Arc<Mutex<R>>,
authorizer: Arc<Mutex<A>>,
}
pub struct IronTokenRequest<A, I> where
A: Authorizer + Send + 'static,
I: Issuer + Send + 'static
{
authorizer: Arc<Mutex<A>>,
issuer: Arc<Mutex<I>>,
}
pub struct IronGuard<I> where
I: Issuer + Send + 'static
{
scopes: Vec<Scope>,
issuer: Arc<Mutex<I>>,
}
impl iron::typemap::Key for AuthenticationRequest { type Value = AuthenticationRequest; }
impl iron::typemap::Key for Authentication { type Value = Authentication; }
pub trait GenericOwnerAuthorizer {
fn get_owner_authorization(&self, &mut iron::Request, AuthenticationRequest) -> Result<(Authentication, iron::Response), OAuthError>;
}
pub struct IronOwnerAuthorizer<A: iron::Handler>(pub A);
impl GenericOwnerAuthorizer for iron::Handler {
fn get_owner_authorization(&self, req: &mut iron::Request, auth: AuthenticationRequest)
-> Result<(Authentication, Response), OAuthError> {
req.extensions.insert::<AuthenticationRequest>(auth);
let response = self.handle(req).map_err(|_| OAuthError::Other("Internal error".to_string()))?;
match req.extensions.get::<Authentication>() {
None => return Ok((Authentication::Failed, Response::with((iron::status::InternalServerError, "No authentication response")))),
Some(v) => return Ok((v.clone(), response)),
};
}
}
impl<F> GenericOwnerAuthorizer for F
where F :Fn(&mut iron::Request, AuthenticationRequest) -> Result<(Authentication, Response), OAuthError> + Send + Sync + 'static {
fn get_owner_authorization(&self, req: &mut iron::Request, auth: AuthenticationRequest)
-> Result<(Authentication, Response), OAuthError> {
self(req, auth)
}
}
impl<A: iron::Handler> GenericOwnerAuthorizer for IronOwnerAuthorizer<A> {
fn get_owner_authorization(&self, req: &mut iron::Request, auth: AuthenticationRequest)
-> Result<(Authentication, Response), OAuthError> {
(&self.0 as &iron::Handler).get_owner_authorization(req, auth)
}
}
struct SpecificOwnerAuthorizer<'l, 'a, 'b: 'a>(&'l GenericOwnerAuthorizer, PhantomData<iron::Request<'a, 'b>>);
impl<'l, 'a, 'b: 'a> OwnerAuthorizer for SpecificOwnerAuthorizer<'l, 'a, 'b> {
type Request = iron::Request<'a, 'b>;
fn get_owner_authorization(&self, req: &mut Self::Request, auth: AuthenticationRequest)
-> Result<(Authentication, Response), OAuthError> {
self.0.get_owner_authorization(req, auth)
}
}
impl<'a, 'b> WebRequest for iron::Request<'a, 'b> {
type Response = iron::Response;
fn query(&mut self) -> Result<HashMap<String, Vec<String>>, ()> {
self.get::<UrlEncodedQuery>().map_err(|_| ())
}
fn urlbody(&mut self) -> Result<&HashMap<String, Vec<String>>, ()> {
self.get_ref::<UrlEncodedBody>().map_err(|_| ())
}
fn authheader(&mut self) -> Result<Option<Cow<str>>, ()> {
let string = match self.headers.get::<AuthHeader<String>>() {
None => return Ok(None),
Some(hdr) => hdr,
};
let position = string.find(' ').ok_or(())?;
let (scheme, content) = string.split_at(position);
Ok(Some(Cow::Borrowed(&content[1..])))
}
}
impl WebResponse for iron::Response {
fn redirect(url: Url) -> Result<Response, OAuthError> {
let real_url = match iron::Url::from_generic_url(url) {
Err(_) => return Err(OAuthError::Other("Error parsing redirect target".to_string())),
Ok(v) => v,
};
Ok(Response::with((iron::status::Found, Redirect(real_url))))
}
fn text(text: &str) -> Result<Response, OAuthError> {
Ok(Response::with((iron::status::Ok, text)))
}
fn json(data: &str) -> Result<Response, OAuthError> {
Ok(Response::with((
iron::status::Ok,
iron::modifiers::Header(iron::headers::ContentType::json()),
data,
)))
}
fn as_client_error(mut self) -> Result<Self, OAuthError> {
self.status = Some(iron::status::BadRequest);
Ok(self)
}
fn as_unauthorized(mut self) -> Result<Self, OAuthError> {
self.status = Some(iron::status::Unauthorized);
Ok(self)
}
fn with_authorization(mut self, kind: &str) -> Result<Self, OAuthError> {
self.headers.set_raw("WWW-Authenticate", vec![kind.as_bytes().to_vec()]);
Ok(self)
}
}
impl<R, A, I> IronGranter<R, A, I> where
R: Registrar + Send + 'static,
A: Authorizer + Send + 'static,
I: Issuer + Send + 'static
{
pub fn new(registrar: R, data: A, issuer: I) -> IronGranter<R, A, I> {
IronGranter {
registrar: Arc::new(Mutex::new(registrar)),
authorizer: Arc::new(Mutex::new(data)),
issuer: Arc::new(Mutex::new(issuer)) }
}
pub fn authorize<H: GenericOwnerAuthorizer + Send + Sync>(&self, page_handler: H) -> IronAuthorizer<H, R, A> {
IronAuthorizer {
authorizer: self.authorizer.clone(),
page_handler: Box::new(page_handler),
registrar: self.registrar.clone() }
}
pub fn token(&self) -> IronTokenRequest<A, I> {
IronTokenRequest { authorizer: self.authorizer.clone(), issuer: self.issuer.clone() }
}
pub fn guard<S>(&self, scopes: S) -> IronGuard<I> where S: Into<Vec<Scope>> {
IronGuard { issuer: self.issuer.clone(), scopes: scopes.into() }
}
pub fn registrar(&self) -> LockResult<MutexGuard<R>> {
self.registrar.lock()
}
pub fn authorizer(&self) -> LockResult<MutexGuard<A>> {
self.authorizer.lock()
}
pub fn issuer(&self) -> LockResult<MutexGuard<I>> {
self.issuer.lock()
}
}
fn from_oauth_error(error: OAuthError) -> IronResult<Response> {
match error {
_ => Ok(Response::with(iron::status::InternalServerError))
}
}
impl From<OAuthError> for IronError {
fn from(this: OAuthError) -> IronError {
IronError::new(this, iron::status::Unauthorized)
}
}
impl<PH, R, A> iron::Handler for IronAuthorizer<PH, R, A> where
PH: GenericOwnerAuthorizer + Send + Sync + 'static,
R: Registrar + Send + 'static,
A: Authorizer + Send + 'static
{
fn handle<'a>(&'a self, req: &mut iron::Request) -> IronResult<Response> {
let prepared = match AuthorizationFlow::prepare(req).map_err(from_oauth_error) {
Err(res) => return res,
Ok(v) => v,
};
let mut locked_registrar = self.registrar.lock().unwrap();
let mut locked_authorizer = self.authorizer.lock().unwrap();
let code = CodeRef::with(locked_registrar.deref_mut(), locked_authorizer.deref_mut());
let handler = SpecificOwnerAuthorizer(self.page_handler.as_ref(), PhantomData);
AuthorizationFlow::handle(code, prepared, &handler).or_else(from_oauth_error)
}
}
impl<A, I> iron::Handler for IronTokenRequest<A, I> where
A: Authorizer + Send + 'static,
I: Issuer + Send + 'static
{
fn handle<'a>(&'a self, req: &mut iron::Request) -> IronResult<Response> {
let prepared = match GrantFlow::prepare(req).map_err(from_oauth_error) {
Err(res) => return res,
Ok(v) => v,
};
let mut locked_authorizer = self.authorizer.lock().unwrap();
let mut locked_issuer = self.issuer.lock().unwrap();
let issuer = IssuerRef::with(locked_authorizer.deref_mut(), locked_issuer.deref_mut());
GrantFlow::handle(issuer, prepared).or_else(from_oauth_error)
}
}
impl<I> iron::BeforeMiddleware for IronGuard<I> where
I: Issuer + Send + 'static
{
fn before(&self, request: &mut Request) -> IronResult<()> {
let prepared = AccessFlow::prepare(request)?;
let mut locked_issuer = self.issuer.lock().unwrap();
let guard = GuardRef::with(locked_issuer.deref_mut(), &self.scopes);
let ok = AccessFlow::handle(guard, prepared)?;
Ok(ok)
}
}
pub mod prelude {
pub use url::Url;
pub use code_grant::prelude::*;
pub use super::{IronGranter, IronOwnerAuthorizer, AuthenticationRequest, Authentication, OAuthError};
}