Skip to content

Commit

Permalink
feat(serde): use serde instead of rustc_serialize
Browse files Browse the repository at this point in the history
That way, we can pretty-print the respective application secret
strucures. This is primiarily of interest for the main client of this
library, namely Google APIs RS.

Version incremented.

Fixes #2
  • Loading branch information
Byron committed Apr 30, 2015
1 parent 3ca51cc commit e05e555
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 29 deletions.
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]

name = "yup-oauth2"
version = "0.3.10"
version = "0.4.0"
authors = ["Sebastian Thiel <byronimo@gmail.com>"]
repository = "https://github.com/Byron/yup-oauth2"
description = "A partial oauth2 implementation, providing the 'device' authorization flow"
Expand All @@ -17,7 +17,8 @@ log = "*"
mime = "*"
url = "*"
itertools = "*"
rustc-serialize = "*"
serde = "*"
serde_macros = "*"

[dev-dependencies]
getopts = "*"
Expand Down
12 changes: 6 additions & 6 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub trait Flow {
fn type_id() -> FlowType;
}

#[derive(RustcDecodable)]
#[derive(Deserialize)]
pub struct JsonError {
pub error: String,
pub error_description: Option<String>,
Expand Down Expand Up @@ -85,7 +85,7 @@ impl FromStr for Scheme {
/// absolute terms.
///
/// Utility methods make common queries easier, see `expired()`.
#[derive(Clone, PartialEq, Debug, RustcDecodable, RustcEncodable)]
#[derive(Clone, PartialEq, Debug, Deserialize, Serialize)]
pub struct Token {
/// used when authenticating calls to oauth2 enabled services.
pub access_token: String,
Expand Down Expand Up @@ -150,7 +150,7 @@ impl AsRef<str> for FlowType {

/// Represents either 'installed' or 'web' applications in a json secrets file.
/// See `ConsoleApplicationSecret` for more information
#[derive(RustcDecodable, RustcEncodable, Clone, Default)]
#[derive(Deserialize, Serialize, Clone, Default)]
pub struct ApplicationSecret {
/// The client ID.
pub client_id: String,
Expand All @@ -173,7 +173,7 @@ pub struct ApplicationSecret {

/// A type to facilitate reading and writing the json secret file
/// as returned by the [google developer console](https://code.google.com/apis/console)
#[derive(RustcDecodable, RustcEncodable, Default)]
#[derive(Deserialize, Serialize, Default)]
pub struct ConsoleApplicationSecret {
pub web: Option<ApplicationSecret>,
pub installed: Option<ApplicationSecret>
Expand All @@ -189,8 +189,8 @@ pub mod tests {

#[test]
fn console_secret() {
use rustc_serialize::json;
match json::decode::<ConsoleApplicationSecret>(SECRET) {
use serde::json;
match json::from_str::<ConsoleApplicationSecret>(SECRET) {
Ok(s) => assert!(s.installed.is_some() && s.web.is_none()),
Err(err) => panic!(err),
}
Expand Down
21 changes: 11 additions & 10 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use hyper;
use hyper::header::ContentType;
use url::form_urlencoded;
use itertools::Itertools;
use rustc_serialize::json;
use serde::json;
use chrono::{DateTime,UTC};
use std::borrow::BorrowMut;
use std::io::Read;
Expand Down Expand Up @@ -202,7 +202,7 @@ impl<C> DeviceFlow<C>
Ok(mut res) => {


#[derive(RustcDecodable)]
#[derive(Deserialize)]
struct JsonData {
device_code: String,
user_code: String,
Expand All @@ -212,17 +212,18 @@ impl<C> DeviceFlow<C>
}

let mut json_str = String::new();
res.read_to_string(&mut json_str).ok().expect("string decode must work");
res.read_to_string(&mut json_str).unwrap();

// check for error
match json::decode::<JsonError>(&json_str) {
match json::from_str::<JsonError>(&json_str) {
Err(_) => {}, // ignore, move on
Ok(res) => {
return Err(RequestError::from(res))
}
}

let decoded: JsonData = json::decode(&json_str).ok().expect("valid reply thanks to valid client_id and client_secret");
println!("{:?}", json_str);
let decoded: JsonData = json::from_str(&json_str).unwrap();

self.device_code = decoded.device_code;
let pi = PollInformation {
Expand Down Expand Up @@ -294,17 +295,17 @@ impl<C> DeviceFlow<C>
}
Ok(mut res) => {
let mut json_str = String::new();
res.read_to_string(&mut json_str).ok().expect("string decode must work");
res.read_to_string(&mut json_str).unwrap();
json_str
}
};

#[derive(RustcDecodable)]
#[derive(Deserialize)]
struct JsonError {
error: String
}

match json::decode::<JsonError>(&json_str) {
match json::from_str::<JsonError>(&json_str) {
Err(_) => {}, // ignore, move on, it's not an error
Ok(res) => {
match res.error.as_ref() {
Expand All @@ -320,7 +321,7 @@ impl<C> DeviceFlow<C>
}

// yes, we expect that !
let mut t: Token = json::decode(&json_str).unwrap();
let mut t: Token = json::from_str(&json_str).unwrap();
t.set_expiry_absolute();

let res = Ok(Some(t.clone()));
Expand All @@ -345,7 +346,7 @@ pub mod tests {
\"device_code\" : \"4/L9fTtLrhY96442SEuf1Rl3KLFg3y\",\r\n\
\"user_code\" : \"a9xfwk9c\",\r\n\
\"verification_url\" : \"http://www.google.com/device\",\r\n\
\"expires_in\" : \"1800\",\r\n\
\"expires_in\" : 1800,\r\n\
\"interval\" : 0\r\n\
}"
"HTTP/1.1 200 OK\r\n\
Expand Down
4 changes: 2 additions & 2 deletions src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -481,9 +481,9 @@ mod tests {

#[test]
fn flow() {
use rustc_serialize::json;
use serde::json;

let secret = json::decode::<ConsoleApplicationSecret>(SECRET).unwrap().installed.unwrap();
let secret = json::from_str::<ConsoleApplicationSecret>(SECRET).unwrap().installed.unwrap();
let res = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
hyper::Client::with_connector(<MockGoogleAuth as Default>::default()),
<MemoryStorage as Default>::default(), None)
Expand Down
12 changes: 8 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@
//! The returned `Token` should be stored permanently to authorize future API requests.
//!
//! ```test_harness,no_run
//! #![feature(custom_derive, plugin)]
//! #![plugin(serde_macros)]
//! extern crate hyper;
//! extern crate yup_oauth2 as oauth2;
//! extern crate rustc_serialize;
//! extern crate serde;
//!
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, PollInformation, ConsoleApplicationSecret, MemoryStorage, GetToken};
//! use rustc_serialize::json;
//! use serde::json;
//! use std::default::Default;
//! # const SECRET: &'static str = "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"UqkDJd5RFwnHoiG5x5Rub8SI\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"14070749909-vgip2f1okm7bkvajhi9jugan6126io9v.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}";
//!
//! # #[test] fn device() {
//! let secret = json::decode::<ConsoleApplicationSecret>(SECRET).unwrap().installed.unwrap();
//! let secret = json::from_str::<ConsoleApplicationSecret>(SECRET).unwrap().installed.unwrap();
//! let res = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! hyper::Client::new(),
//! <MemoryStorage as Default>::default(), None)
Expand Down Expand Up @@ -59,6 +61,8 @@
//! };
//! # }
//! ```
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate chrono;

#[macro_use]
Expand All @@ -71,7 +75,7 @@ extern crate mime;
extern crate url;
extern crate time;
extern crate itertools;
extern crate rustc_serialize as rustc_serialize;
extern crate serde;


mod device;
Expand Down
10 changes: 5 additions & 5 deletions src/refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use device::GOOGLE_TOKEN_URL;
use chrono::UTC;
use hyper;
use hyper::header::ContentType;
use rustc_serialize::json;
use serde::json;
use url::form_urlencoded;
use super::Token;
use std::borrow::BorrowMut;
Expand Down Expand Up @@ -83,27 +83,27 @@ impl<C> RefreshFlow<C>
}
Ok(mut res) => {
let mut json_str = String::new();
res.read_to_string(&mut json_str).ok().expect("string decode must work");
res.read_to_string(&mut json_str).unwrap();
json_str
}
};

#[derive(RustcDecodable)]
#[derive(Deserialize)]
struct JsonToken {
access_token: String,
token_type: String,
expires_in: i64,
}

match json::decode::<JsonError>(&json_str) {
match json::from_str::<JsonError>(&json_str) {
Err(_) => {},
Ok(res) => {
self.result = RefreshResult::RefreshError(res.error, res.error_description);
return &self.result;
}
}

let t: JsonToken = json::decode(&json_str).unwrap();
let t: JsonToken = json::from_str(&json_str).unwrap();
self.result = RefreshResult::Success(Token {
access_token: t.access_token,
token_type: t.token_type,
Expand Down

0 comments on commit e05e555

Please sign in to comment.