#![allow(unknown_lints, doc_markdown)]
use std::sync::{Arc, Mutex};
use hyper;
use hyper::header::{Headers, Authorization, Basic, Bearer, UserAgent};
use std::io::Read;
use serde_json;
use responses::auth::TokenResponse;
use hyper::client::Client;
use errors::APIError;
pub trait Authenticator {
fn login(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError>;
fn refresh_token(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError> {
self.login(client, user_agent)
}
fn logout(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError>;
fn scopes(&self) -> Vec<String>;
fn headers(&self) -> Headers;
fn oauth(&self) -> bool;
}
pub struct AnonymousAuthenticator;
impl Authenticator for AnonymousAuthenticator {
#[allow(unused_variables)]
fn login(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError> {
Ok(())
}
#[allow(unused_variables)]
fn logout(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError> {
Ok(())
}
fn scopes(&self) -> Vec<String> {
vec![String::from("read")]
}
fn headers(&self) -> Headers {
Headers::new()
}
fn oauth(&self) -> bool {
false
}
}
impl AnonymousAuthenticator {
pub fn new() -> Arc<Mutex<Box<Authenticator + Send>>> {
Arc::new(Mutex::new(Box::new(AnonymousAuthenticator {})))
}
}
pub struct PasswordAuthenticator {
access_token: Option<String>,
client_id: String,
client_secret: String,
username: String,
password: String
}
impl Authenticator for PasswordAuthenticator {
fn login(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError> {
let url = "https://www.reddit.com/api/v1/access_token";
let body = format!("grant_type=password&username={}&password={}", &self.username, &self.password);
let access_req = client.post(url).header(Authorization(
Basic {
username: self.client_id.to_owned(),
password: Some(self.client_secret.to_owned())
}
)).header(UserAgent(user_agent.to_owned())).body(&body);
let mut result = access_req.send().unwrap();
if result.status != hyper::Ok {
Err(APIError::HTTPError(result.status))
} else {
let mut buf = String::new();
result.read_to_string(&mut buf).unwrap();
let token_response: TokenResponse = serde_json::from_str(&buf).unwrap();
self.access_token = Some(token_response.access_token);
Ok(())
}
}
fn logout(&mut self, client: &Client, user_agent: &str) -> Result<(), APIError> {
let url = "https://www.reddit.com/api/v1/revoke_token";
let body = format!("token={}", &self.access_token.to_owned().unwrap());
let req = client.post(url).header(Authorization(
Basic {
username: self.client_id.to_owned(),
password: Some(self.client_secret.to_owned())
}
)).header(UserAgent(user_agent.to_owned())).body(&body);
let res = req.send().unwrap();
if !res.status.is_success() {
Err(APIError::HTTPError(res.status))
} else {
Ok(())
}
}
fn scopes(&self) -> Vec<String> {
vec![String::from("*")]
}
fn headers(&self) -> Headers {
let mut headers = Headers::new();
if let Some(ref token) = self.access_token {
headers.set(Authorization(
Bearer {
token: token.to_owned()
}
));
}
headers
}
fn oauth(&self) -> bool {
true
}
}
impl PasswordAuthenticator {
pub fn new(client_id: &str, client_secret: &str, username: &str, password: &str) -> Arc<Mutex<Box<Authenticator + Send>>> {
Arc::new(Mutex::new(Box::new(PasswordAuthenticator {
client_id: client_id.to_owned(),
client_secret: client_secret.to_owned(),
username: username.to_owned(),
password: password.to_owned(),
access_token: None
})))
}
}