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
#![cfg_attr(test, deny(warnings))]
//! A library for making oauth2 requests with updated depencies like curl 0.3.0
//!
//! # Examples
//!
//! ```rust,no_run,ignore
//! extern crate rustc_serialize;
//! extern crate oauth-api;
//!
//! use rustc_serialize::json;
//! use std::fs::File;
//! use std::io::Read;
//! /* Secrets.json sample contents:
//! {
//!   "client_id": "abcde",
//!   "client_secret": "efgab",
//!   "auth_url": "https://github.com/login/oauth/authorize",
//!   "token_url": "https://github.com/login/oauth/access_token"
//! }
//! */
//! let mut f = File::open("secrets.json").unwrap();
//! let mut read_str = String::new();
//! let _ = f.read_to_string(&mut read_str);
//! let sec : Secret = json::decode(&read_str).unwrap();
//!
//! let mut conf = oauth2::Config::new(
//!     &sec.client_id,
//!     &sec.client_secret,
//!     &sec.auth_url,
//!     &sec.token_url
//! );
//! conf.scopes = vec!["repo".to_owned()];
//! let url = conf.authorize_url("v0.0.1 gitbot".to_owned());
//! println!("please visit this url: {}", url);
//!
//! let mut user_code = String::new();
//! let _ = std::io::stdin().read_line(&mut user_code).unwrap();
//! user_code.pop();
//! let tok = conf.exchange(user_code).unwrap();
//! println!("access code is: {}", tok.access_token);
//! ```
//!

extern crate url;
extern crate curl;
#[macro_use] extern crate log;

use url::Url;
use std::sync::{Arc,Mutex};
use std::io::Read;

use curl::easy::{Easy, List};

/// Configuration of an oauth2 application.
pub struct Config {
    pub client_id: String,
    pub client_secret: String,
    pub scopes: Vec<String>,
    pub auth_url: Url,
    pub token_url: Url,
    pub redirect_url: String,
}

/// Represents a Token struct
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd)]
pub struct Token {
    /// access token used to authenticate queries
    pub access_token: String,
    /// A vec of scopes
    pub scopes: Vec<String>,
    /// 'bearer', etc...
    pub token_type: String,
}

struct ErrorContainer {
    error : String,
    error_desc : String,
    error_uri : String
}

impl ErrorContainer {
    fn new() -> ErrorContainer {
        ErrorContainer {
            error: String::new(),
            error_desc: String::new(),
            error_uri: String::new()
        }
    }
}

macro_rules! try_error_to_string {
    ($e:expr) => (match $e {
        Ok(val) => val,
        Err(err) => return Err(::std::convert::From::from(error_to_string(err))),
    });
}


/// Helper trait for extending the builder-style pattern of curl::easy::Easy.
///
/// This trait allows chaining the correct authorization headers onto a curl
/// request via the builder style.
pub trait Authorization {
    fn auth_with(&mut self, token: &Token) -> Result<(), curl::Error>;
}

impl Config {

    /// Generates a new config from the given fields
    pub fn new(id: &str, secret: &str, auth_url: &str,
               token_url: &str) -> Config {
        Config {
            client_id: id.to_string(),
            client_secret: secret.to_string(),
            scopes: Vec::new(),
            auth_url: Url::parse(auth_url).unwrap(),
            token_url: Url::parse(token_url).unwrap(),
            redirect_url: String::new(),
        }
    }

    #[allow(deprecated)] // connect => join in 1.3
    /// Generates an auth url to visit from the infomation in the config struct
    pub fn authorize_url(&self, state: String) -> Url {
        let scopes = self.scopes.connect(",");
        let mut pairs = vec![
            ("client_id", &self.client_id),
            ("state", &state),
            ("scope", &scopes),
        ];
        if self.redirect_url.len() > 0 {
            pairs.push(("redirect_uri", &self.redirect_url));
        }
        let mut url = self.auth_url.clone();

        for (k,v) in pairs {
            url.query_pairs_mut().append_pair(k,v);
        }
        return url;
    }

    /// Given a code (obtained from the authorize_url) and varies by service.
    /// exchange will then make a POST request with the code and attempt to retrieve an access token.
    /// On success, the token is returned as a Result. On failure, a string with an error description
    /// is returned as a Result
    pub fn exchange(&self, code: String) -> Result<Token, String> {
        let mut form = url::form_urlencoded::Serializer::new(String::new());
        form.append_pair("client_id", &self.client_id.clone());
        form.append_pair("client_secret", &self.client_secret.clone());
        form.append_pair("code", &code);
        if self.redirect_url.len() > 0 {
            form.append_pair("redirect_uri", &self.redirect_url.clone());
        }

        let form_str : String = form.finish();
        let post_len = form_str.as_bytes().len();

        let mut easy = Easy::new();
        try_error_to_string!(easy.url(&self.token_url.to_string()));
        let mut list = List::new();
        try_error_to_string!(list.append("Content-Type: application/x-www-form-urlencoded"));
        try_error_to_string!(easy.http_headers(list));
        try_error_to_string!(easy.show_header(true));
        try_error_to_string!(easy.read_function(move |buf| {
            Ok(form_str.as_bytes().read(buf).unwrap_or(0))
        }));
        try_error_to_string!(easy.post(true));
        try_error_to_string!(easy.post_field_size(post_len as u64));

        let token = Token {
            access_token: String::new(),
            scopes: Vec::new(),
            token_type: String::new(),
        };

        let protector = Arc::new(Mutex::new(token));
        let result_ref = protector.clone();
        let error_strings = Arc::new(Mutex::new(ErrorContainer::new()));
        let error_strings_copy = error_strings.clone();

        try_error_to_string!(easy.write_function(move |data| {
            let mut result_token = result_ref.lock().unwrap();
            let mut err_cont = error_strings_copy.lock().unwrap();

            let result_form = url::form_urlencoded::parse(data);
            for(k, v) in result_form.into_iter() {
                match &k[..] {
                    "access_token" => result_token.access_token = (*v).to_owned(),
                    "token_type" => result_token.token_type = (*v).to_owned(),
                    "scope" => {
                        result_token.scopes = v.split(',')
                                        .map(|s| s.to_string()).collect();
                    },
                     "error" => err_cont.error = (*v).to_owned(),
                     "error_description" => err_cont.error_desc = (*v).to_owned(),
                     "error_uri" => err_cont.error_uri = (*v).to_owned(),
                    _ => {}
                }
            }
            return Ok(data.len());
        }));

        try_error_to_string!(easy.perform());

        let resp_code = try_error_to_string!(easy.response_code());
        if resp_code != 200 {
            return Err(format!("expected `200`, found `{}`", resp_code))
        }

        let new_token = protector.lock().unwrap();
        let new_errors = error_strings.lock().unwrap();

        if new_token.access_token.len() != 0 {
            Ok(new_token.clone())
        } else if new_errors.error.len() > 0 {
            Err(format!("error `{}`: {}, see {}", new_errors.error, new_errors.error_desc, new_errors.error_uri))
        } else {
            Err(format!("couldn't find access_token in the response"))
        }
    }
}

fn error_to_string(e : curl::Error) -> String {
    let err_str : &str;
    err_str = if e.is_unsupported_protocol() {
        "Unsupported Protocol!"
    } else if e.is_failed_init() {
        "Failed to initialize"
    } else if e.is_url_malformed() {
        "Url is malformed!"
    } else if e.is_couldnt_resolve_proxy() {
        "Couldn't resolve proxy"
    } else if e.is_couldnt_resolve_host() {
        "Couldn't Resolve host"
    } else if e.is_couldnt_connect() {
        "Couldn't Connect"
    } else if e.is_remote_access_denied() {
        "Remote access is denied"
    } else if e.is_partial_file() {
        "Partial file given"
    } else if e.is_quote_error() {
        "Quote error"
    } else if e.is_http_returned_error() {
        "Http returned error"
    } else if e.is_read_error() {
        "Read error"
    } else if e.is_write_error() {
        "Write Error"
    } else if e.is_upload_failed() {
        "Upload failed"
    } else if e.is_out_of_memory() {
        "Out of memory"
    } else if e.is_operation_timedout() {
        "Timed out"
    } else if e.is_range_error() {
        "Range error"
    } else if e.is_http_post_error() {
        "Http post error"
    } else if e.is_ssl_connect_error() {
        "SSL connect error"
    } else if e.is_bad_download_resume() {
        "Bad download resume error"
    } else if e.is_file_couldnt_read_file() {
        "Cannot read given file"
    } else if e.is_function_not_found() {
        "Cannot find given function error"
    } else if e.is_aborted_by_callback() {
        "Callback aborted error"
    } else if e.is_bad_function_argument() {
        "Bad function argument error"
    } else if e.is_interface_failed() {
        "Interface failed error"
    } else if e.is_too_many_redirects() {
        "Too many redirects error"
    } else if e.is_unknown_option() {
        "Unknown option error"
    } else if e.is_peer_failed_verification() {
        "Peer failed to validate error"
    } else if e.is_got_nothing() {
        "Received nothing error"
    } else if e.is_ssl_engine_notfound() {
        "SSL engine not found error"
    } else if e.is_ssl_engine_setfailed() {
        "SSL engine set failed error"
    } else if e.is_send_error() {
        "Send failed error"
    } else if e.is_recv_error() {
        "Recieve failed error"
    } else if e.is_ssl_certproblem() {
        "SSL certificate problem error"
    } else if e.is_ssl_cipher() {
        "SSL cipher error"
    } else if e.is_ssl_cacert() {
        "SSL CA Cert error"
    } else if e.is_bad_content_encoding() {
        "Bad content encoding error"
    } else if e.is_filesize_exceeded() {
        "Filesize exceeded error"
    } else if e.is_use_ssl_failed() {
        "Use SSL failed error"
    } else if e.is_send_fail_rewind() {
        "Send rewind fail error"
    } else if e.is_ssl_engine_initfailed() {
        "SSL engine init fail error"
    } else if e.is_login_denied() {
        "Login denied error"
    } else if e.is_conv_failed() {
        "Conv failed error"
    } else if e.is_conv_required() {
        "Conv required error"
    } else if e.is_ssl_cacert_badfile() {
        "CA cert bad file error"
    } else if e.is_ssl_crl_badfile() {
        "SSL crl bad file error"
    } else if e.is_ssl_shutdown_failed() {
        "SSL Shutdown failed error"
    } else if e.is_again() {
        "Again error"
    } else if e.is_ssl_issuer_error() {
        "SSL Issuer error"
    } else if e.is_chunk_failed() {
        "Chunk failed error"
    } else {
        "general error"
    };
    return err_str.to_string();
}

/// Given a curl::easy::Easy and a `Token` struct, it adds the Authorization: access_token header
/// to the request. It return curl::Error when adding the header fails.
impl Authorization for curl::easy::Easy{
    fn auth_with(&mut self, token: &Token) -> Result<(), curl::Error> {
        let mut auth_header = List::new();
        let auth_header_text = format!("Authorization: {}", token.access_token);
        let res = auth_header.append(&auth_header_text);
        if res.is_ok() {
            self.http_headers(auth_header)
        } else {
            res
        }
    }
}