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
//! The functions to get your access token for
//! [3-legged OAuth](https://dev.twitter.com/oauth/3-legged) or
//! [PIN-based OAuth](https://dev.twitter.com/oauth/pin-based).

use hyper::{Post, Url};
use oauthcli::{self, SignatureMethod};
use url::form_urlencoded;
use ::{OAuthAuthenticator, TwitterError, TwitterResult};
use conn::request_twitter;
use conn::Parameter::Value;

#[derive(Clone, Debug)]
pub struct RequestTokenResponse {
    consumer_key: String,
    consumer_secret: String,
    pub oauth_token: String,
    pub oauth_token_secret: String,
    pub oauth_callback_confirmed: bool
}

impl RequestTokenResponse {
    pub fn access_token(&self, oauth_verifier: &str) -> AccessTokenRequestBuilder {
        access_token(
            &self.consumer_key[..],
            &self.consumer_secret[..],
            &self.oauth_token[..],
            &self.oauth_token_secret[..],
            oauth_verifier
        )
    }
}

#[derive(Clone, Debug)]
pub struct RequestTokenRequestBuilder {
    consumer_key: String,
    consumer_secret: String,
    oauth_callback: String,
    x_auth_access_type: Option<String>
}

impl RequestTokenRequestBuilder {
    pub fn x_auth_access_type(mut self, val: &str) -> RequestTokenRequestBuilder {
        self.x_auth_access_type = Some(val.to_string());
        self
    }

    pub fn execute(&self) -> TwitterResult<RequestTokenResponse> {
        let request_token_url = Url::parse("https://api.twitter.com/oauth/request_token").unwrap();
        let mut params = Vec::new();
        match self.x_auth_access_type {
            Some(ref x) => params.push(Value("x_auth_access_type", x.clone())),
            None => ()
        }
        let authorization = oauthcli::authorization_header(
            "POST",
            request_token_url.clone(),
            None,
            &self.consumer_key[..],
            &self.consumer_secret[..],
            None,
            None,
            SignatureMethod::HmacSha1,
            &oauthcli::timestamp()[..],
            &oauthcli::nonce()[..],
            Some(&self.oauth_callback[..]),
            None,
            params.iter().map(|x| match x {
                &Value(key, ref val) => (key.to_string(), val.clone()),
                _ => unreachable!()
            })
        );
        let res = try!(request_twitter(
            Post, request_token_url.clone(), &params[..], authorization));
        let v = form_urlencoded::parse(res.raw_response.as_bytes()).collect::<Vec<_>>();
        let oauth_token = v.iter().find(|x| x.0 == "oauth_token");
        let oauth_token_secret = v.iter().find(|x| x.0 == "oauth_token_secret");
        let oauth_callback_confirmed = v.iter()
            .find(|x| x.0 == "oauth_callback_confirmed")
            .and_then(|x| (&x.1[..]).parse().ok());
        match oauth_token.and(oauth_token_secret) {
            Some(_) => Ok(res.object(RequestTokenResponse {
                consumer_key: self.consumer_key.clone(),
                consumer_secret: self.consumer_secret.clone(),
                oauth_token: oauth_token.unwrap().1.clone().to_string(),
                oauth_token_secret: oauth_token_secret.unwrap().1.clone().to_string(),
                oauth_callback_confirmed: oauth_callback_confirmed.unwrap_or(false)
            })),
            None => Err(TwitterError::ParseError(res.clone()))
        }
    }
}

pub fn request_token(consumer_key: &str, consumer_secret: &str, oauth_callback: &str)
    -> RequestTokenRequestBuilder
{
    RequestTokenRequestBuilder {
        consumer_key: consumer_key.to_string(),
        consumer_secret: consumer_secret.to_string(),
        oauth_callback: oauth_callback.to_string(),
        x_auth_access_type: None
    }
}

#[derive(Clone, Debug)]
pub struct AccessTokenResponse {
    consumer_key: String,
    consumer_secret: String,
    pub oauth_token: String,
    pub oauth_token_secret: String,
    pub user_id: i64,
    pub screen_name: String
}

impl AccessTokenResponse {
    pub fn to_authenticator(&self) -> OAuthAuthenticator {
        OAuthAuthenticator::new(
            &self.consumer_key[..],
            &self.consumer_secret[..],
            &self.oauth_token[..],
            &self.oauth_token_secret[..]
        )
    }
}

#[derive(Clone, Debug)]
pub struct AccessTokenRequestBuilder {
    consumer_key: String,
    consumer_secret: String,
    oauth_token: String,
    oauth_token_secret: String,
    oauth_verifier: String
}

impl AccessTokenRequestBuilder {
    pub fn execute(&self) -> TwitterResult<AccessTokenResponse> {
        let access_token_url = Url::parse("https://api.twitter.com/oauth/access_token").unwrap();
        let authorization = oauthcli::authorization_header(
            "POST",
            access_token_url.clone(),
            None,
            &self.consumer_key[..],
            &self.consumer_secret[..],
            Some(&self.oauth_token[..]),
            Some(&self.oauth_token_secret[..]),
            SignatureMethod::HmacSha1,
            &oauthcli::timestamp()[..],
            &oauthcli::nonce()[..],
            None,
            Some(&self.oauth_verifier[..]),
            Vec::new().into_iter()
        );
        let res = try!(request_twitter(
            Post, access_token_url.clone(), &[], authorization));
        let v = form_urlencoded::parse(res.raw_response.as_bytes()).collect::<Vec<_>>();
        let oauth_token = v.iter().find(|x| x.0 == "oauth_token");
        let oauth_token_secret = v.iter().find(|x| x.0 == "oauth_token_secret");
        let user_id = v.iter().find(|x| x.0 == "user_id")
            .and_then(|x| (&x.1[..]).parse().ok());
        let screen_name = v.iter().find(|x| x.0 == "screen_name");
        match oauth_token.and(oauth_token_secret).and(user_id).and(screen_name) {
            Some(_) => Ok(res.object(AccessTokenResponse {
                consumer_key: self.consumer_key.to_string(),
                consumer_secret: self.consumer_secret.to_string(),
                oauth_token: oauth_token.unwrap().1.clone().to_string(),
                oauth_token_secret: oauth_token_secret.unwrap().1.clone().to_string(),
                user_id: user_id.unwrap(),
                screen_name: screen_name.unwrap().1.clone().to_string()
            })),
            None => Err(TwitterError::ParseError(res.clone()))
        }
    }
}

pub fn access_token(consumer_key: &str, consumer_secret: &str,
    oauth_token: &str, oauth_token_secret: &str, oauth_verifier: &str)
    -> AccessTokenRequestBuilder
{
    AccessTokenRequestBuilder {
        consumer_key: consumer_key.to_string(),
        consumer_secret: consumer_secret.to_string(),
        oauth_token: oauth_token.to_string(),
        oauth_token_secret: oauth_token_secret.to_string(),
        oauth_verifier: oauth_verifier.to_string()
    }
}