From feba2d0e5afe01171bb6ba1289dcf68644c00354 Mon Sep 17 00:00:00 2001 From: Sebastian Thiel Date: Sun, 22 Mar 2015 11:55:05 +0100 Subject: [PATCH] feat(header): Authorization Scheme for Oauth Allows not natively use Oauth2 schemes with hyper Authorization headers. Added support for serialization and parsing. --- Cargo.toml | 2 +- src/common.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 +- 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9f320c41c..ea486675e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "yup-oauth2" -version = "0.3.0" +version = "0.3.1" authors = ["Sebastian Thiel "] repository = "https://github.com/Byron/yup-oauth2" description = "A partial oauth2 implementation, providing the 'device' authorization flow" diff --git a/src/common.rs b/src/common.rs index 39e6db80d..d5684ce66 100644 --- a/src/common.rs +++ b/src/common.rs @@ -1,11 +1,73 @@ use chrono::{DateTime, UTC, TimeZone}; use std::marker::MarkerTrait; +use std::fmt; +use std::str::FromStr; +use hyper; /// A marker trait for all Flows pub trait Flow : MarkerTrait { fn type_id() -> FlowType; } +/// Represents all implemented token types +#[derive(Clone, PartialEq, Debug)] +pub enum TokenType { + /// Means that whoever bears the access token will be granted access + Bearer, +} + +impl Str for TokenType { + fn as_slice(&self) -> &'static str { + match *self { + TokenType::Bearer => "Bearer" + } + } +} + +impl FromStr for TokenType { + type Err = (); + fn from_str(s: &str) -> Result { + match s { + "Bearer" => Ok(TokenType::Bearer), + _ => Err(()) + } + } +} + + +/// A scheme for use in `hyper::header::Authorization` +#[derive(Clone, PartialEq, Debug)] +pub struct Scheme { + /// The type of our access token + pub token_type: TokenType, + /// The token returned by one of the Authorization Flows + pub access_token: String +} + +impl hyper::header::Scheme for Scheme { + fn scheme(_: Option) -> Option<&'static str> { + None + } + + fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} {}", self.token_type.as_slice(), self.access_token) + } +} + +impl FromStr for Scheme { + type Err = &'static str; + fn from_str(s: &str) -> Result { + let parts: Vec<&str> = s.split(' ').collect(); + if parts.len() != 2 { + return Err("Expected two parts: ") + } + match ::from_str(parts[0]) { + Ok(t) => Ok(Scheme { token_type: t, access_token: parts[1].to_string() }), + Err(_) => Err("Couldn't parse token type") + } + } +} + /// Represents a token as returned by OAuth2 servers. /// /// It is produced by all authentication flows. @@ -116,6 +178,7 @@ pub struct ConsoleApplicationSecret { #[cfg(test)] pub mod tests { use super::*; + use hyper; pub 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\"}}"; @@ -127,4 +190,19 @@ pub mod tests { Err(err) => panic!(err), } } + + #[test] + fn schema() { + let s = Scheme {token_type: TokenType::Bearer, access_token: "foo".to_string() }; + let mut headers = hyper::header::Headers::new(); + headers.set(hyper::header::Authorization(s)); + assert_eq!(headers.to_string(), "Authorization: Bearer foo\r\n".to_string()); + } + + #[test] + fn parse_schema() { + let auth: hyper::header::Authorization = hyper::header::Header::parse_header(&[b"Bearer foo".to_vec()]).unwrap(); + assert_eq!(auth.0.token_type, TokenType::Bearer); + assert_eq!(auth.0.access_token, "foo".to_string()); + } } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 69d5251cb..183e8a9cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -82,6 +82,6 @@ mod helper; pub use device::{DeviceFlow, PollInformation, PollResult}; pub use refresh::{RefreshFlow, RefreshResult}; -pub use common::{Token, FlowType, ApplicationSecret, ConsoleApplicationSecret}; +pub use common::{Token, FlowType, ApplicationSecret, ConsoleApplicationSecret, Scheme, TokenType}; pub use helper::{TokenStorage, NullStorage, MemoryStorage, Authenticator, AuthenticatorDelegate, Retry, DefaultAuthenticatorDelegate, GetToken};