Credentials

Struct Credentials 

Source
pub struct Credentials {
    pub client_secrets: ClientSecrets,
    pub access_token: AccessToken,
}
Expand description

Contains the credentials ( ClientSecrets and AccessToken ) for a authorizing requests to the Google Drive API using OAuth 2.0.

§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, once you complete the Authorize credentials for a desktop application section you can use the downloaded secrets file.

§Examples

use drive_v3::Credentials;

let secrets_path = "my_client_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() );

Fields§

§client_secrets: ClientSecrets

Representation of the client_secret.json file that contains the authorization info for your API.

§access_token: AccessToken

Token used to authenticate and provide authorization information to Google APIs.

Implementations§

Source§

impl Credentials

Source

pub fn new(client_secrets: &ClientSecrets, access_token: &AccessToken) -> Self

Creates new Credentials using client_secrets and access_token.

Examples:

use drive_v3::AccessToken;
use drive_v3::{Credentials, Drive};
use drive_v3::ClientSecrets;

// Load your client_secrets file
let secrets_path = "my_client_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);
Source

pub fn get_access_token(&self) -> String

Gets the access token which is sent as a HTTP Authorization request header to the Google Drive API to authenticate access.

Examples:

// 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);
Source

pub fn store<T: AsRef<Path>>(&self, path: T) -> Result<()>

Saves Credentials as a JSON file in path.

§Examples
use drive_v3::Credentials;

// 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);
§Errors
  • a Json error, if unable to parse the Credentials to JSON.
  • an IO error, if unable to write to path.
Source

pub fn refresh(&mut self) -> Result<()>

Refreshes expired or invalid Credentials.

§Note

The refreshed credentials are updated in place, you should save them to a file using the store function to avoid requesting to many new credentials.

§Examples
if !credentials.are_valid() {
    credentials.refresh()?;
}

assert!( credentials.are_valid() );
§Errors
  • a Request error, if unable to send the refresh request or get a body from the response.
  • a Json error, if unable to parse the received token from JSON.
Source

pub fn are_valid(&self) -> bool

Checks if these Credentials are valid by making a request to the tokeninfo endpoint of the Google Drive API.

§Note

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
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");
}
Source

pub fn from_file<T, U>(file: T, scopes: &[U]) -> Result<Self>
where T: AsRef<Path>, U: AsRef<str>,

Retrieves previously stored Credentials from file and checks that they have the required scopes enabled.

§Note

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 function. If they are no longer valid use the refresh function to update them.

§Examples
use drive_v3::Credentials;

let credentials_path = "my_credentials.json";
let scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"];

let credentials = Credentials::from_file(&credentials_path, &scopes)?;
§Errors
  • an IO error, if the file does not exist.
  • a Json error, if parsing of the file from JSON failed.
  • a MismatchedScopes error, if the scopes in the access token are different to the scopes passed to the function.
Source

pub fn from_client_secrets_file<T, U>(file: T, scopes: &[U]) -> Result<Self>
where T: AsRef<Path>, U: AsRef<str>,

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, once you complete the Authorize credentials for a desktop application section you can use the downloaded secrets file.

§Examples
use drive_v3::Credentials;

let secrets_path = "my_client_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() );
§Errors

Trait Implementations§

Source§

impl Clone for Credentials

Source§

fn clone(&self) -> Credentials

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Credentials

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Credentials

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Credentials

Source§

fn eq(&self, other: &Credentials) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Credentials

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Credentials

Source§

impl StructuralPartialEq for Credentials

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,