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
use hyper::client::Client as HttpClient;
use url::Url;
use oauth2::provider::Provider;
use oauth2::client::response::{FromResponse, ParseError};
use oauth2::token::{Lifetime, Token};
use chrono::{DateTime, Duration, NaiveDateTime, UTC};
use rustc_serialize::json::Json;
use serde::{de, ser};
use api::{Id, Request};
use std::ops::BitOr;
use std::iter::FromIterator;
use std::str::FromStr;

pub use oauth2::ClientError as OAuthError;

#[derive(Debug, PartialEq, Eq)]
pub struct AccessTokenLifetime {
    expires: Option<DateTime<UTC>>,
}

impl de::Deserialize for AccessTokenLifetime {
    fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<AccessTokenLifetime, D::Error> {
        de::Deserialize::deserialize(d).map(|ts: Option<u64>| {
            AccessTokenLifetime { expires: ts.map(|ts| DateTime::from_utc(NaiveDateTime::from_timestamp(ts as i64, 0), UTC)) }
        })
    }
}

impl ser::Serialize for AccessTokenLifetime {
    fn serialize<S: ser::Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
        ser::Serialize::serialize(&self.expires.map(|ts| ts.timestamp()), s)
    }
}

#[cfg(feature = "unstable")]
include!("auth.rs.in");

#[cfg(not(feature = "unstable"))]
include!(concat!(env!("OUT_DIR"), "/auth.rs"));

impl FromResponse for AccessTokenLifetime {
    fn from_response(json: &Json) -> Result<AccessTokenLifetime, ParseError> {
        json.find("expires_in")
            .and_then(Json::as_i64)
            .map(|expires_in| {
                AccessTokenLifetime { expires: if expires_in > 0 { Some(UTC::now() + Duration::seconds(expires_in)) } else { None } }
            })
            .ok_or_else(|| ParseError::ExpectedFieldType("expires_in", "i64"))
    }
}

impl FromResponse for AccessToken {
    fn from_response(json: &Json) -> Result<AccessToken, ParseError> {
        Ok(AccessToken {
            email: json.find("email").and_then(Json::as_string).map(ToOwned::to_owned),
            user_id: try!(json.find("user_id")
                              .and_then(Json::as_u64)
                              .ok_or(ParseError::ExpectedFieldType("user_id", "u64"))),
            access_token: try!(json.find("access_token")
                                   .and_then(Json::as_string)
                                   .map(ToOwned::to_owned)
                                   .ok_or(ParseError::ExpectedFieldType("access_token", "string"))),
            lifetime: try!(AccessTokenLifetime::from_response(json)),
        })
    }
}

impl Lifetime for AccessTokenLifetime {
    fn expired(&self) -> bool {
        self.expires.map_or(false, |e| e <= UTC::now())
    }
}

impl Token<AccessTokenLifetime> for AccessToken {
    fn access_token(&self) -> &str {
        &*self.access_token
    }
    fn scope(&self) -> Option<&str> {
        None
    }
    fn lifetime(&self) -> &AccessTokenLifetime {
        &self.lifetime
    }
}

impl AccessToken {
    pub fn expired(&self) -> bool {
        self.lifetime.expired()
    }
}

pub struct OAuth<'a>(::oauth2::client::Client<Auth>, &'a HttpClient);

impl<'a> OAuth<'a> {
    pub fn new(client: &'a HttpClient, key: String, secret: String) -> OAuth {
        OAuth(::oauth2::client::Client::<Auth>::new(key, secret, Some(String::from(OAUTH_DEFAULT_REDIRECT_URI))), client)
    }
    pub fn auth_uri<T: Into<Permissions>>(&self, scope: T) -> Result<Url, OAuthError> {
        let scope: String = scope.into().into();
        self.0.auth_uri(Some(&scope), None)
    }
    pub fn auth_uri_for<T: Request>(&self) -> Result<Url, OAuthError> {
        let scope = <T as Request>::permissions();
        self.auth_uri(scope)
    }
    pub fn request_token(&self, code: &str) -> Result<AccessToken, OAuthError> {
        self.0.request_token(self.1, code)
    }
}

pub struct Auth;
impl Provider for Auth {
    type Lifetime = AccessTokenLifetime;
    type Token = AccessToken;
    fn auth_uri() -> &'static str {
        "https://oauth.vk.com/authorize"
    }
    fn token_uri() -> &'static str {
        "https://oauth.vk.com/access_token"
    }
    fn credentials_in_body() -> bool {
        true
    }
}

pub static OAUTH_DEFAULT_REDIRECT_URI: &'static str = "https://oauth.vk.com/blank.html";

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[allow(overflowing_literals)]
#[repr(i32)]
pub enum Permission {
    Notify = 1,
    Friends = 2,
    Photos = 4,
    Audio = 8,
    Video = 16,
    Docs = 131072,
    Notes = 2048,
    Pages = 128,
    Menu = 256,
    Status = 1024,
    Offers = 32,
    Questions = 64,
    Wall = 8192,
    Groups = 262144,
    Messages = 4096,
    Email = 4194304,
    Notifications = 524288,
    Stats = 1048576,
    Ads = 32768,
    Market = 134217728,
    Offline = 65536,
    NoHttps = 0x8000_0000 as i32, // unofficial
}

static PERMISSIONS: &'static [Permission] = &[Permission::Notify,
                                              Permission::Friends,
                                              Permission::Photos,
                                              Permission::Audio,
                                              Permission::Video,
                                              Permission::Docs,
                                              Permission::Notes,
                                              Permission::Pages,
                                              Permission::Menu,
                                              Permission::Status,
                                              Permission::Offers,
                                              Permission::Questions,
                                              Permission::Wall,
                                              Permission::Groups,
                                              Permission::Messages,
                                              Permission::Email,
                                              Permission::Notifications,
                                              Permission::Stats,
                                              Permission::Ads,
                                              Permission::Market,
                                              Permission::Offline,
                                              Permission::NoHttps];

impl Permission {
    pub fn variants() -> &'static [Permission] {
        PERMISSIONS
    }

    pub fn mask(&self) -> i32 {
        *self as i32
    }

    pub fn mask_all() -> i32 {
        0x5ebdff
    }

    pub fn to_str(&self) -> &'static str {
        use self::Permission::*;
        match *self {
            Notify => "notify",
            Friends => "friends",
            Photos => "photos",
            Audio => "audio",
            Video => "video",
            Docs => "docs",
            Notes => "notes",
            Pages => "pages",
            Menu => "menu",
            Status => "status",
            Offers => "offers",
            Questions => "questions",
            Wall => "wall",
            Groups => "groups",
            Messages => "messages",
            Email => "email",
            Notifications => "notifications",
            Stats => "stats",
            Ads => "ads",
            Market => "market",
            Offline => "offline",
            NoHttps => "nohttps",
        }
    }
}

impl FromStr for Permission {
    type Err = ();
    fn from_str(s: &str) -> Result<Permission, ()> {
        use self::Permission::*;
        Ok(match s {
            "notify" => Notify,
            "friends" => Friends,
            "photos" => Photos,
            "audio" => Audio,
            "video" => Video,
            "docs" => Docs,
            "notes" => Notes,
            "pages" => Pages,
            "menu" => Menu,
            "status" => Status,
            "offers" => Offers,
            "questions" => Questions,
            "wall" => Wall,
            "groups" => Groups,
            "messages" => Messages,
            "email" => Email,
            "notifications" => Notifications,
            "stats" => Stats,
            "ads" => Ads,
            "market" => Market,
            "offline" => Offline,
            "nohttps" => NoHttps,
            _ => return Err(()),
        })
    }
}

#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
pub struct Permissions(i32);

impl Permissions {
    pub fn new(n: i32) -> Permissions {
        Permissions(n & Permission::mask_all())
    }
}

impl de::Deserialize for Permissions {
    fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<Permissions, D::Error> {
        de::Deserialize::deserialize(d).map(Permissions::new)
    }
}

impl FromStr for Permissions {
    type Err = ();
    fn from_str(s: &str) -> Result<Permissions, ()> {
        s.split(',').map(str::trim).map(Permission::from_str).collect()
    }
}

impl From<Permission> for Permissions {
    fn from(perm: Permission) -> Permissions {
        Permissions(perm as i32)
    }
}

impl<'a, T: IntoIterator<Item = &'a Permission>> From<T> for Permissions {
    fn from(iter: T) -> Permissions {
        iter.into_iter().collect()
    }
}

impl FromIterator<i32> for Permissions {
    fn from_iter<T: IntoIterator<Item = i32>>(iter: T) -> Permissions {
        Permissions(iter.into_iter().fold(0, BitOr::bitor))
    }
}

impl FromIterator<Permission> for Permissions {
    fn from_iter<T: IntoIterator<Item = Permission>>(iter: T) -> Permissions {
        Permissions(iter.into_iter().map(|perm| perm as i32).fold(0, BitOr::bitor))
    }
}

impl<'a> FromIterator<&'a Permission> for Permissions {
    fn from_iter<T: IntoIterator<Item = &'a Permission>>(iter: T) -> Permissions {
        Permissions(iter.into_iter().map(|&perm| perm as i32).fold(0, BitOr::bitor))
    }
}

impl Into<String> for Permissions {
    fn into(self) -> String {
        Into::<Vec<&'static str>>::into(self).join(",")
    }
}

impl Into<Vec<Permission>> for Permissions {
    fn into(self) -> Vec<Permission> {
        let Permissions(n) = self;
        Permission::variants()
            .iter()
            .filter(|&&mask| mask as i32 & n != 0)
            .cloned()
            .collect()
    }
}

impl Into<Vec<&'static str>> for Permissions {
    fn into(self) -> Vec<&'static str> {
        let Permissions(n) = self;
        Permission::variants()
            .iter()
            .filter(|&&mask| mask as i32 & n != 0)
            .map(Permission::to_str)
            .collect()
    }
}