drive-v3 0.6.0

A library for interacting the Google Drive API
Documentation
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use std::{fs, path::Path};
use serde::{Deserialize, Serialize};

use crate::{Error, ErrorKind};
use crate::AccessToken;
use crate::ClientSecrets;

/// Contains the credentials ( [`ClientSecrets`](crate::ClientSecrets) and
/// [`AccessToken`](crate::AccessToken) ) for a authorizing requests to the Google Drive API using
/// [OAuth 2.0](https://developers.google.com/identity/protocols/oauth2).
///
/// # Note:
///
/// When creating credentials a `client_secrets` JSON file is required in order to use OAuth2 to authorize your API.
///
/// If you do not have a `client_secrets` JSON file, follow
/// [these steps](https://developers.google.com/drive/api/quickstart/python#set_up_your_environment), once you complete the
/// [Authorize credentials for a desktop application](https://developers.google.com/drive/api/quickstart/python#authorize_credentials_for_a_desktop_application)
/// section you can use the downloaded secrets file.
///
/// # Examples
///
/// ```no_run
/// use drive_v3::Credentials;
/// # use drive_v3::Error;
///
/// let secrets_path = "my_client_secrets.json";
/// # let secrets_path = "../.secure-files/google_drive_secrets.json";
/// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
///
/// let credentials = Credentials::from_client_secrets_file(&secrets_path, &scopes)?;
///
/// assert!( credentials.are_valid() );
/// # Ok::<(), Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Credentials {
    /// Representation of the `client_secret.json` file that contains the authorization info for your API.
    pub client_secrets: ClientSecrets,

    /// Token used to authenticate and provide authorization information to Google APIs.
    pub access_token: AccessToken,
}

impl Credentials {
    /// Creates new [`Credentials`] using `client_secrets` and `access_token`.
    ///
    /// Examples:
    ///
    /// ```no_run
    /// use drive_v3::AccessToken;
    /// use drive_v3::{Credentials, Drive};
    /// use drive_v3::ClientSecrets;
    /// # use drive_v3::Error;
    ///
    /// // Load your client_secrets file
    /// let secrets_path = "my_client_secrets.json";
    /// # let secrets_path = "../.secure-files/google_drive_secrets.json";
    /// let my_client_secrets = ClientSecrets::from_file(secrets_path)?;
    ///
    /// // Request an access token, this will prompt you to authorize via the browser
    /// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// let my_access_token = AccessToken::request(&my_client_secrets, &scopes)?;
    ///
    /// // Create Credentials
    /// let my_credentials = Credentials::new(&my_client_secrets, &my_access_token);
    ///
    /// // now you can create a Drive to make requests
    /// let drive = Drive::new(&my_credentials);
    /// let files = drive.files.list();
    ///
    /// println!("files in drive: {:#?}", files);
    ///
    /// # Ok::<(), Error>(())
    /// ```
    pub fn new( client_secrets: &ClientSecrets, access_token: &AccessToken ) -> Self {
        Self {
            client_secrets: client_secrets.clone(),
            access_token: access_token.clone(),
        }
    }

    /// Gets the [access token](https://cloud.google.com/docs/authentication/token-types#access) which is sent as a
    /// [HTTP Authorization request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) to the
    /// Google Drive API to authenticate access.
    ///
    /// Examples:
    ///
    /// ```no_run
    /// # use drive_v3::Credentials;
    /// # use drive_v3::Error;
    /// #
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// # let credentials_path = "../.secure-files/google_drive_credentials.json";
    /// #
    /// # let mut credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// #
    /// // You can use this token to make a requests (with reqwest for example) using it for authorization
    /// let client = reqwest::blocking::Client::new();
    ///
    /// let body = client.get("google-api-endpoint")
    ///     .bearer_auth( &credentials.get_access_token() )
    ///     .send()?
    ///     .text()?;
    ///
    /// println!("response: {:?}", body);
    /// # Ok::<(), Error>(())
    /// ```
    pub fn get_access_token( &self ) -> String {
        self.access_token.access_token.to_string()
    }

    /// Saves [`Credentials`] as a JSON file in `path`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use drive_v3::Credentials;
    /// #
    /// # use drive_v3::Error;
    /// #
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// # let credentials_path = "../.secure-files/google_drive_credentials.json";
    /// #
    /// # let mut credentials = Credentials::from_file(&credentials_path, &scopes)?;
    ///
    /// // Store credentials for the next time you need authorization
    /// credentials.store("credentials_new.json")?;
    ///
    /// let required_scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// let stored_credentials = Credentials::from_file("credentials_new.json", &required_scopes)?;
    ///
    /// assert_eq!(credentials, stored_credentials);
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the [`Credentials`] to JSON.
    /// - an [`IO`](crate::ErrorKind::IO) error, if unable to write to `path`.
    pub fn store<T: AsRef<Path>> ( &self, path: T ) -> crate::Result<()> {
        let contents = serde_json::to_string(&self)?;
        fs::write(&path, contents)?;

        Ok(())
    }

    /// Refreshes expired or invalid [`Credentials`].
    ///
    /// # Note
    ///
    /// The refreshed credentials are updated in place, you should save them to a file using the [`store`](Credentials::store)
    /// function to avoid requesting to many new credentials.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use drive_v3::{Credentials, Error};
    /// #
    /// # let credentials_path = "../.secure-files/google_drive_credentials.json";
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// #
    /// # let mut credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// #
    /// if !credentials.are_valid() {
    ///     credentials.refresh()?;
    /// }
    ///
    /// assert!( credentials.are_valid() );
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - a [`Request`](crate::ErrorKind::Request) error, if unable to send the refresh request or get a body from the response.
    /// - a [`Json`](crate::ErrorKind::Json) error, if unable to parse the received token from JSON.
    pub fn refresh( &mut self ) -> crate::Result<()> {
        self.access_token.refresh( &self.client_secrets )
    }

    /// Checks if these [`Credentials`] are valid by making a request to the
    /// [tokeninfo](https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint) endpoint of
    /// the Google Drive API.
    ///
    /// # Note
    ///
    /// [`are_valid`](Credentials::are_valid) will return false if the credentials have expired or have been revoked, but it will
    /// also return false if the tokeninfo endpoint cannot be reached or if the request returned an error response of any kind.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use drive_v3::{Credentials, Error};
    /// #
    /// # let credentials_path = "../.secure-files/google_drive_credentials.json";
    /// # let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    /// #
    /// # let credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// #
    /// if credentials.are_valid() {
    ///     println!("credentials are valid!, you can start making requests");
    /// } else {
    ///     println!("credentials are invalid :c, try calling 'credentials.refresh()' to update them");
    /// }
    /// # Ok::<(), Error>(())
    /// ```
    pub fn are_valid( &self ) -> bool {
        self.access_token.is_valid()
    }

    /// Retrieves previously stored [`Credentials`] from `file` and checks that they have the required `scopes` enabled.
    ///
    /// # Note
    ///
    /// [`from_file`](Credentials::from_file) only parses the stored credentials it does not validate them, before using them to
    /// make requests you must ensure that they are still valid using the [`are_valid`](Credentials::are_valid) function.
    /// If they are no longer valid use the [`refresh`](Credentials::refresh) function to update them.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use drive_v3::Credentials;
    /// # use drive_v3::Error;
    ///
    /// let credentials_path = "my_credentials.json";
    /// # let credentials_path = "../.secure-files/google_drive_credentials.json";
    /// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    ///
    /// let credentials = Credentials::from_file(&credentials_path, &scopes)?;
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - an [`IO`](crate::ErrorKind::IO) error, if the file does not exist.
    /// - a [`Json`](crate::ErrorKind::Json) error, if parsing of the file from JSON failed.
    /// - a [`MismatchedScopes`](crate::ErrorKind::MismatchedScopes) error, if the scopes in the access token are different
    /// to the `scopes` passed to the function.
    pub fn from_file<T, U> ( file: T, scopes: &[U] ) -> crate::Result<Self>
        where
            T: AsRef<Path>,
            U: AsRef<str>,
    {
        let contents = fs::read_to_string(&file)?;
        let credentials: Credentials = serde_json::from_str(&contents)?;

        if !credentials.access_token.has_scopes(scopes) {
            return Err(
                Error::new(ErrorKind::MismatchedScopes, "stored access token does not contain the requested scopes")
            )
        }

        Ok(credentials)
    }

    /// Attempts to get [`Credentials`] by prompting the user for authorization.
    ///
    /// # Note:
    ///
    /// A `client_secrets` json file is required in order to use OAuth2 to authorize your API.
    ///
    /// If you do not have a `client_secrets` json file, follow
    /// [these steps](https://developers.google.com/drive/api/quickstart/python#set_up_your_environment), once you complete the
    /// [Authorize credentials for a desktop application](https://developers.google.com/drive/api/quickstart/python#authorize_credentials_for_a_desktop_application)
    /// section you can use the downloaded secrets file.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use drive_v3::Credentials;
    /// # use drive_v3::Error;
    ///
    /// let secrets_path = "my_client_secrets.json";
    /// # let secrets_path = "../.secure-files/google_drive_secrets.json";
    /// let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];
    ///
    /// let credentials = Credentials::from_client_secrets_file(&secrets_path, &scopes)?;
    ///
    /// assert!( credentials.are_valid() );
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - an [`IO`](crate::ErrorKind::IO) or [`Json`](crate::ErrorKind::Json) error, if unable get
    /// [`ClientSecrets`](crate::ClientSecrets) from `file`.
    /// - a [`HexDecoding`](crate::ErrorKind::HexDecoding), [`UrlParsing`](crate::ErrorKind::UrlParsing),
    /// [`Request`](crate::ErrorKind::Request) or [`Response`](crate::ErrorKind::Response) error, if the
    /// get access token request fails.
    /// - a [`MismatchedScopes`](crate::ErrorKind::MismatchedScopes) error, if the scopes in the created access token are
    /// different to the `scopes` passed to the function.
    #[cfg(not(tarpaulin_include))]
    pub fn from_client_secrets_file<T, U> ( file: T, scopes: &[U] ) -> crate::Result<Self>
        where
            T: AsRef<Path>,
            U: AsRef<str>,
    {
        let client_secrets = ClientSecrets::from_file(&file)?;
        let access_token = AccessToken::request(&client_secrets, scopes)?;

        Ok( Self::new(&client_secrets, &access_token) )
    }
}

#[cfg(test)]
mod tests {
    use serde_json;
    use super::ErrorKind;
    use super::Credentials;
    use std::process::Command;
    use testfile::{self, TestFile};
    use crate::utils::test::{VALID_CREDENTIALS, VALID_SECRETS};

    fn get_test_json() -> String {
        String::from("{
            \"client_secrets\": {
                \"client_id\": \"test\",
                \"project_id\": \"test\",
                \"auth_uri\": \"test\",
                \"token_uri\": \"test\",
                \"auth_provider_x509_cert_url\": \"test\",
                \"client_secret\": \"test\",
                \"redirect_uris\": [\"test\"]
            },
            \"access_token\": {
                \"access_token\": \"test\",
                \"expires_in\": 0,
                \"refresh_token\": \"test\",
                \"scope\": \"test-scope other-test-scope unchecked-scope\",
                \"token_type\": \"test\"
            }
        }")
    }

    fn get_test_scopes() -> Vec<String> {
        vec![
            String::from("test-scope"),
            String::from("other-test-scope"),
        ]
    }

    fn get_test_credentials_file() -> TestFile {
        testfile::from( &get_test_json() )
    }

    #[test]
    fn new_test() {
        let client_secrets = VALID_SECRETS.clone();
        let access_token = VALID_CREDENTIALS.access_token.clone();

        let credentials = Credentials::new(&client_secrets, &access_token);

        assert_eq!(credentials.client_secrets, client_secrets);
        assert_eq!(credentials.access_token, access_token);
    }

    #[test]
    fn get_access_token_test() {
        let credentials = VALID_CREDENTIALS.clone();

        assert_eq!( credentials.access_token.access_token, credentials.get_access_token() );
    }

    #[test]
    fn refresh_test() {
        let mut credentials = VALID_CREDENTIALS.clone();
        let result = credentials.refresh();

        assert!( result.is_ok() );
    }

    #[test]
    fn store_test() {
        let scopes: [&str; 0] = [];
        let credentials = VALID_CREDENTIALS.clone();

        credentials.store("test-stored-credentials.json").unwrap();

        let saved_credentials = Credentials::from_file("test-stored-credentials.json", &scopes).unwrap();

        Command::new("rm").arg("test-stored-credentials.json").output().unwrap();

        assert_eq!(saved_credentials, credentials);
    }

    #[test]
    fn are_valid_test() {
        let scopes = get_test_scopes();
        let test_file = get_test_credentials_file();

        let credentials = Credentials::from_file(&test_file, &scopes).unwrap();

        assert!( !credentials.are_valid() );
    }

    #[test]
    fn from_file_test() {
        let scopes = get_test_scopes();
        let test_file = get_test_credentials_file();
        let expected_credentials = serde_json::from_str( &get_test_json() ).unwrap();

        let credentials = Credentials::from_file(&test_file, &scopes).unwrap();

        assert_eq!(credentials, expected_credentials);
    }

    #[test]
    fn from_file_invalid_scopes_test() {
        let scopes = ["invalid-scope"];
        let test_file = get_test_credentials_file();

        let result = Credentials::from_file(&test_file, &scopes);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::MismatchedScopes );
    }

    #[test]
    fn from_file_non_existent_test() {
        let scopes = get_test_scopes();
        let test_file = "non-existent.json";

        let result = Credentials::from_file(&test_file, &scopes);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::IO );
    }

    #[test]
    fn from_file_invalid_json_test() {
        let scopes = get_test_scopes();
        let test_file =  testfile::from("This is not JSON");

        let result = Credentials::from_file(&test_file, &scopes);

        assert!( result.is_err() );
        assert_eq!( result.unwrap_err().kind, ErrorKind::Json );
    }

    #[test]
    fn from_file_no_longer_valid_test() {
        let scopes = get_test_scopes();
        let test_file = get_test_credentials_file();

        let credentials = Credentials::from_file(&test_file, &scopes).unwrap();

        assert_eq!( credentials.are_valid(), false );
    }
}