RPM build fix (reverted CI changes which will need to be un-reverted or made conditional) and vendor Rust dependencies to make builds much faster in any CI system.
This commit is contained in:
147
zeroidc/vendor/oauth2/examples/github.rs
vendored
Normal file
147
zeroidc/vendor/oauth2/examples/github.rs
vendored
Normal file
@@ -0,0 +1,147 @@
|
||||
//!
|
||||
//! This example showcases the Github OAuth2 process for requesting access to the user's public repos and
|
||||
//! email address.
|
||||
//!
|
||||
//! Before running it, you'll need to generate your own Github OAuth2 credentials.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! GITHUB_CLIENT_ID=xxx GITHUB_CLIENT_SECRET=yyy cargo run --example github
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::basic::BasicClient;
|
||||
|
||||
// Alternatively, this can be `oauth2::curl::http_client` or a custom client.
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::{
|
||||
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope,
|
||||
TokenResponse, TokenUrl,
|
||||
};
|
||||
use std::env;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
fn main() {
|
||||
let github_client_id = ClientId::new(
|
||||
env::var("GITHUB_CLIENT_ID").expect("Missing the GITHUB_CLIENT_ID environment variable."),
|
||||
);
|
||||
let github_client_secret = ClientSecret::new(
|
||||
env::var("GITHUB_CLIENT_SECRET")
|
||||
.expect("Missing the GITHUB_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
let auth_url = AuthUrl::new("https://github.com/login/oauth/authorize".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://github.com/login/oauth/access_token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
|
||||
// Set up the config for the Github OAuth2 process.
|
||||
let client = BasicClient::new(
|
||||
github_client_id,
|
||||
Some(github_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
// This example will be running its own server at localhost:8080.
|
||||
// See below for the server implementation.
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
|
||||
);
|
||||
|
||||
// Generate the authorization URL to which we'll redirect the user.
|
||||
let (authorize_url, csrf_state) = client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
// This example is requesting access to the user's public repos and email.
|
||||
.add_scope(Scope::new("public_repo".to_string()))
|
||||
.add_scope(Scope::new("user:email".to_string()))
|
||||
.url();
|
||||
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\n",
|
||||
authorize_url.to_string()
|
||||
);
|
||||
|
||||
// A very naive implementation of the redirect server.
|
||||
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
||||
for stream in listener.incoming() {
|
||||
if let Ok(mut stream) = stream {
|
||||
let code;
|
||||
let state;
|
||||
{
|
||||
let mut reader = BufReader::new(&stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line).unwrap();
|
||||
|
||||
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
|
||||
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
|
||||
|
||||
let code_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "code"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = code_pair;
|
||||
code = AuthorizationCode::new(value.into_owned());
|
||||
|
||||
let state_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "state"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = state_pair;
|
||||
state = CsrfToken::new(value.into_owned());
|
||||
}
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
message
|
||||
);
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
|
||||
println!("Github returned the following code:\n{}\n", code.secret());
|
||||
println!(
|
||||
"Github returned the following state:\n{} (expected `{}`)\n",
|
||||
state.secret(),
|
||||
csrf_state.secret()
|
||||
);
|
||||
|
||||
// Exchange the code with a token.
|
||||
let token_res = client.exchange_code(code).request(http_client);
|
||||
|
||||
println!("Github returned the following token:\n{:?}\n", token_res);
|
||||
|
||||
if let Ok(token) = token_res {
|
||||
// NB: Github returns a single comma-separated "scope" parameter instead of multiple
|
||||
// space-separated scopes. Github-specific clients can parse this scope into
|
||||
// multiple scopes by splitting at the commas. Note that it's not safe for the
|
||||
// library to do this by default because RFC 6749 allows scopes to contain commas.
|
||||
let scopes = if let Some(scopes_vec) = token.scopes() {
|
||||
scopes_vec
|
||||
.iter()
|
||||
.map(|comma_separated| comma_separated.split(','))
|
||||
.flatten()
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
println!("Github returned the following scopes:\n{:?}\n", scopes);
|
||||
}
|
||||
|
||||
// The server will terminate itself after collecting the first code.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
151
zeroidc/vendor/oauth2/examples/github_async.rs
vendored
Normal file
151
zeroidc/vendor/oauth2/examples/github_async.rs
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
//!
|
||||
//! This example showcases the Github OAuth2 process for requesting access to the user's public repos and
|
||||
//! email address.
|
||||
//!
|
||||
//! Before running it, you'll need to generate your own Github OAuth2 credentials.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! GITHUB_CLIENT_ID=xxx GITHUB_CLIENT_SECRET=yyy cargo run --example github
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::basic::BasicClient;
|
||||
|
||||
// Alternatively, this can be `oauth2::curl::http_client` or a custom client.
|
||||
use oauth2::reqwest::async_http_client;
|
||||
use oauth2::{
|
||||
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope,
|
||||
TokenResponse, TokenUrl,
|
||||
};
|
||||
use std::env;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let github_client_id = ClientId::new(
|
||||
env::var("GITHUB_CLIENT_ID").expect("Missing the GITHUB_CLIENT_ID environment variable."),
|
||||
);
|
||||
let github_client_secret = ClientSecret::new(
|
||||
env::var("GITHUB_CLIENT_SECRET")
|
||||
.expect("Missing the GITHUB_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
let auth_url = AuthUrl::new("https://github.com/login/oauth/authorize".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://github.com/login/oauth/access_token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
|
||||
// Set up the config for the Github OAuth2 process.
|
||||
let client = BasicClient::new(
|
||||
github_client_id,
|
||||
Some(github_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
// This example will be running its own server at localhost:8080.
|
||||
// See below for the server implementation.
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
|
||||
);
|
||||
|
||||
// Generate the authorization URL to which we'll redirect the user.
|
||||
let (authorize_url, csrf_state) = client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
// This example is requesting access to the user's public repos and email.
|
||||
.add_scope(Scope::new("public_repo".to_string()))
|
||||
.add_scope(Scope::new("user:email".to_string()))
|
||||
.url();
|
||||
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\n",
|
||||
authorize_url.to_string()
|
||||
);
|
||||
|
||||
// A very naive implementation of the redirect server.
|
||||
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
|
||||
loop {
|
||||
if let Ok((mut stream, _)) = listener.accept().await {
|
||||
let code;
|
||||
let state;
|
||||
{
|
||||
let mut reader = BufReader::new(&mut stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line).await.unwrap();
|
||||
|
||||
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
|
||||
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
|
||||
|
||||
let code_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "code"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = code_pair;
|
||||
code = AuthorizationCode::new(value.into_owned());
|
||||
|
||||
let state_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "state"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = state_pair;
|
||||
state = CsrfToken::new(value.into_owned());
|
||||
}
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
message
|
||||
);
|
||||
stream.write_all(response.as_bytes()).await.unwrap();
|
||||
|
||||
println!("Github returned the following code:\n{}\n", code.secret());
|
||||
println!(
|
||||
"Github returned the following state:\n{} (expected `{}`)\n",
|
||||
state.secret(),
|
||||
csrf_state.secret()
|
||||
);
|
||||
|
||||
// Exchange the code with a token.
|
||||
let token_res = client
|
||||
.exchange_code(code)
|
||||
.request_async(async_http_client)
|
||||
.await;
|
||||
|
||||
println!("Github returned the following token:\n{:?}\n", token_res);
|
||||
|
||||
if let Ok(token) = token_res {
|
||||
// NB: Github returns a single comma-separated "scope" parameter instead of multiple
|
||||
// space-separated scopes. Github-specific clients can parse this scope into
|
||||
// multiple scopes by splitting at the commas. Note that it's not safe for the
|
||||
// library to do this by default because RFC 6749 allows scopes to contain commas.
|
||||
let scopes = if let Some(scopes_vec) = token.scopes() {
|
||||
scopes_vec
|
||||
.iter()
|
||||
.map(|comma_separated| comma_separated.split(','))
|
||||
.flatten()
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
println!("Github returned the following scopes:\n{:?}\n", scopes);
|
||||
}
|
||||
|
||||
// The server will terminate itself after collecting the first code.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
162
zeroidc/vendor/oauth2/examples/google.rs
vendored
Normal file
162
zeroidc/vendor/oauth2/examples/google.rs
vendored
Normal file
@@ -0,0 +1,162 @@
|
||||
//!
|
||||
//! This example showcases the Google OAuth2 process for requesting access to the Google Calendar features
|
||||
//! and the user's profile.
|
||||
//!
|
||||
//! Before running it, you'll need to generate your own Google OAuth2 credentials.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::{basic::BasicClient, revocation::StandardRevocableToken, TokenResponse};
|
||||
// Alternatively, this can be oauth2::curl::http_client or a custom.
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::{
|
||||
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
|
||||
RevocationUrl, Scope, TokenUrl,
|
||||
};
|
||||
use std::env;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
fn main() {
|
||||
let google_client_id = ClientId::new(
|
||||
env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
|
||||
);
|
||||
let google_client_secret = ClientSecret::new(
|
||||
env::var("GOOGLE_CLIENT_SECRET")
|
||||
.expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://www.googleapis.com/oauth2/v3/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
|
||||
// Set up the config for the Google OAuth2 process.
|
||||
let client = BasicClient::new(
|
||||
google_client_id,
|
||||
Some(google_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
// This example will be running its own server at localhost:8080.
|
||||
// See below for the server implementation.
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
|
||||
)
|
||||
// Google supports OAuth 2.0 Token Revocation (RFC-7009)
|
||||
.set_revocation_uri(
|
||||
RevocationUrl::new("https://oauth2.googleapis.com/revoke".to_string())
|
||||
.expect("Invalid revocation endpoint URL"),
|
||||
);
|
||||
|
||||
// Google supports Proof Key for Code Exchange (PKCE - https://oauth.net/2/pkce/).
|
||||
// Create a PKCE code verifier and SHA-256 encode it as a code challenge.
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
// Generate the authorization URL to which we'll redirect the user.
|
||||
let (authorize_url, csrf_state) = client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
// This example is requesting access to the "calendar" features and the user's profile.
|
||||
.add_scope(Scope::new(
|
||||
"https://www.googleapis.com/auth/calendar".to_string(),
|
||||
))
|
||||
.add_scope(Scope::new(
|
||||
"https://www.googleapis.com/auth/plus.me".to_string(),
|
||||
))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\n",
|
||||
authorize_url.to_string()
|
||||
);
|
||||
|
||||
// A very naive implementation of the redirect server.
|
||||
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
||||
for stream in listener.incoming() {
|
||||
if let Ok(mut stream) = stream {
|
||||
let code;
|
||||
let state;
|
||||
{
|
||||
let mut reader = BufReader::new(&stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line).unwrap();
|
||||
|
||||
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
|
||||
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
|
||||
|
||||
let code_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "code"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = code_pair;
|
||||
code = AuthorizationCode::new(value.into_owned());
|
||||
|
||||
let state_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "state"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = state_pair;
|
||||
state = CsrfToken::new(value.into_owned());
|
||||
}
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
message
|
||||
);
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
|
||||
println!("Google returned the following code:\n{}\n", code.secret());
|
||||
println!(
|
||||
"Google returned the following state:\n{} (expected `{}`)\n",
|
||||
state.secret(),
|
||||
csrf_state.secret()
|
||||
);
|
||||
|
||||
// Exchange the code with a token.
|
||||
let token_response = client
|
||||
.exchange_code(code)
|
||||
.set_pkce_verifier(pkce_code_verifier)
|
||||
.request(http_client);
|
||||
|
||||
println!(
|
||||
"Google returned the following token:\n{:?}\n",
|
||||
token_response
|
||||
);
|
||||
|
||||
// Revoke the obtained token
|
||||
let token_response = token_response.unwrap();
|
||||
let token_to_revoke: StandardRevocableToken = match token_response.refresh_token() {
|
||||
Some(token) => token.into(),
|
||||
None => token_response.access_token().into(),
|
||||
};
|
||||
|
||||
client
|
||||
.revoke_token(token_to_revoke)
|
||||
.unwrap()
|
||||
.request(http_client)
|
||||
.expect("Failed to revoke token");
|
||||
|
||||
// The server will terminate itself after revoking the token.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
82
zeroidc/vendor/oauth2/examples/google_devicecode.rs
vendored
Normal file
82
zeroidc/vendor/oauth2/examples/google_devicecode.rs
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
//!
|
||||
//! This example showcases the Google OAuth2 process for requesting access to the Google Calendar features
|
||||
//! and the user's profile.
|
||||
//!
|
||||
//! Before running it, you'll need to generate your own Google OAuth2 credentials.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=yyy cargo run --example google
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::basic::BasicClient;
|
||||
// Alternatively, this can be oauth2::curl::http_client or a custom.
|
||||
use oauth2::devicecode::{DeviceAuthorizationResponse, ExtraDeviceAuthorizationFields};
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::{AuthType, AuthUrl, ClientId, ClientSecret, DeviceAuthorizationUrl, Scope, TokenUrl};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct StoringFields(HashMap<String, serde_json::Value>);
|
||||
|
||||
impl ExtraDeviceAuthorizationFields for StoringFields {}
|
||||
type StoringDeviceAuthorizationResponse = DeviceAuthorizationResponse<StoringFields>;
|
||||
|
||||
fn main() {
|
||||
let google_client_id = ClientId::new(
|
||||
env::var("GOOGLE_CLIENT_ID").expect("Missing the GOOGLE_CLIENT_ID environment variable."),
|
||||
);
|
||||
let google_client_secret = ClientSecret::new(
|
||||
env::var("GOOGLE_CLIENT_SECRET")
|
||||
.expect("Missing the GOOGLE_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://www.googleapis.com/oauth2/v3/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let device_auth_url =
|
||||
DeviceAuthorizationUrl::new("https://oauth2.googleapis.com/device/code".to_string())
|
||||
.expect("Invalid device authorization endpoint URL");
|
||||
|
||||
// Set up the config for the Google OAuth2 process.
|
||||
//
|
||||
// Google's OAuth endpoint expects the client_id to be in the request body,
|
||||
// so ensure that option is set.
|
||||
let device_client = BasicClient::new(
|
||||
google_client_id,
|
||||
Some(google_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
.set_device_authorization_url(device_auth_url)
|
||||
.set_auth_type(AuthType::RequestBody);
|
||||
|
||||
// Request the set of codes from the Device Authorization endpoint.
|
||||
let details: StoringDeviceAuthorizationResponse = device_client
|
||||
.exchange_device_code()
|
||||
.unwrap()
|
||||
.add_scope(Scope::new("profile".to_string()))
|
||||
.request(http_client)
|
||||
.expect("Failed to request codes from device auth endpoint");
|
||||
|
||||
// Display the URL and user-code.
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\nand enter the code: {}",
|
||||
details.verification_uri().to_string(),
|
||||
details.user_code().secret().to_string()
|
||||
);
|
||||
|
||||
// Now poll for the token
|
||||
let token = device_client
|
||||
.exchange_device_access_token(&details)
|
||||
.request(http_client, std::thread::sleep, None)
|
||||
.expect("Failed to get token");
|
||||
|
||||
println!("Google returned the following token:\n{:?}\n", token);
|
||||
}
|
||||
133
zeroidc/vendor/oauth2/examples/letterboxd.rs
vendored
Normal file
133
zeroidc/vendor/oauth2/examples/letterboxd.rs
vendored
Normal file
@@ -0,0 +1,133 @@
|
||||
//!
|
||||
//! This example showcases the Letterboxd OAuth2 process for requesting access
|
||||
//! to the API features restricted by authentication. Letterboxd requires all
|
||||
//! requests being signed as described in http://api-docs.letterboxd.com/#signing.
|
||||
//! So this serves as an example how to implement a custom client, which signs
|
||||
//! requests and appends the signature to the url query.
|
||||
//!
|
||||
//! Before running it, you'll need to get access to the API.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! LETTERBOXD_CLIENT_ID=xxx LETTERBOXD_CLIENT_SECRET=yyy LETTERBOXD_USERNAME=www LETTERBOXD_PASSWORD=zzz cargo run --example letterboxd
|
||||
//! ```
|
||||
|
||||
use hex::ToHex;
|
||||
use hmac::{Hmac, Mac};
|
||||
use oauth2::{
|
||||
basic::BasicClient, AuthType, AuthUrl, ClientId, ClientSecret, HttpRequest, HttpResponse,
|
||||
ResourceOwnerPassword, ResourceOwnerUsername, TokenUrl,
|
||||
};
|
||||
use sha2::Sha256;
|
||||
use url::Url;
|
||||
|
||||
use std::env;
|
||||
use std::time;
|
||||
|
||||
fn main() -> Result<(), anyhow::Error> {
|
||||
// a.k.a api key in Letterboxd API documentation
|
||||
let letterboxd_client_id = ClientId::new(
|
||||
env::var("LETTERBOXD_CLIENT_ID")
|
||||
.expect("Missing the LETTERBOXD_CLIENT_ID environment variable."),
|
||||
);
|
||||
// a.k.a api secret in Letterboxd API documentation
|
||||
let letterboxd_client_secret = ClientSecret::new(
|
||||
env::var("LETTERBOXD_CLIENT_SECRET")
|
||||
.expect("Missing the LETTERBOXD_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
// Letterboxd uses the Resource Owner flow and does not have an auth url
|
||||
let auth_url = AuthUrl::new("https://api.letterboxd.com/api/v0/auth/404".to_string())?;
|
||||
let token_url = TokenUrl::new("https://api.letterboxd.com/api/v0/auth/token".to_string())?;
|
||||
|
||||
// Set up the config for the Letterboxd OAuth2 process.
|
||||
let client = BasicClient::new(
|
||||
letterboxd_client_id.clone(),
|
||||
Some(letterboxd_client_secret.clone()),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
);
|
||||
|
||||
// Resource Owner flow uses username and password for authentication
|
||||
let letterboxd_username = ResourceOwnerUsername::new(
|
||||
env::var("LETTERBOXD_USERNAME")
|
||||
.expect("Missing the LETTERBOXD_USERNAME environment variable."),
|
||||
);
|
||||
let letterboxd_password = ResourceOwnerPassword::new(
|
||||
env::var("LETTERBOXD_PASSWORD")
|
||||
.expect("Missing the LETTERBOXD_PASSWORD environment variable."),
|
||||
);
|
||||
|
||||
// All API requests must be signed as described at http://api-docs.letterboxd.com/#signing;
|
||||
// for that, we use a custom http client.
|
||||
let http_client = SigningHttpClient::new(letterboxd_client_id, letterboxd_client_secret);
|
||||
|
||||
let token_result = client
|
||||
.set_auth_type(AuthType::RequestBody)
|
||||
.exchange_password(&letterboxd_username, &letterboxd_password)
|
||||
.request(|request| http_client.execute(request))?;
|
||||
|
||||
println!("{:?}", token_result);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Custom HTTP client which signs requests.
|
||||
///
|
||||
/// See http://api-docs.letterboxd.com/#signing.
|
||||
#[derive(Debug, Clone)]
|
||||
struct SigningHttpClient {
|
||||
client_id: ClientId,
|
||||
client_secret: ClientSecret,
|
||||
}
|
||||
|
||||
impl SigningHttpClient {
|
||||
fn new(client_id: ClientId, client_secret: ClientSecret) -> Self {
|
||||
Self {
|
||||
client_id,
|
||||
client_secret,
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs the request before calling `oauth2::reqwest::http_client`.
|
||||
fn execute(&self, mut request: HttpRequest) -> Result<HttpResponse, impl std::error::Error> {
|
||||
let signed_url = self.sign_url(request.url, &request.method, &request.body);
|
||||
request.url = signed_url;
|
||||
oauth2::reqwest::http_client(request)
|
||||
}
|
||||
|
||||
/// Signs the request based on a random and unique nonce, timestamp, and
|
||||
/// client id and secret.
|
||||
///
|
||||
/// The client id, nonce, timestamp and signature are added to the url's
|
||||
/// query.
|
||||
///
|
||||
/// See http://api-docs.letterboxd.com/#signing.
|
||||
fn sign_url(&self, mut url: Url, method: &http::method::Method, body: &[u8]) -> Url {
|
||||
let nonce = uuid::Uuid::new_v4(); // use UUID as random and unique nonce
|
||||
|
||||
let timestamp = time::SystemTime::now()
|
||||
.duration_since(time::UNIX_EPOCH)
|
||||
.expect("SystemTime::duration_since failed")
|
||||
.as_secs();
|
||||
|
||||
url.query_pairs_mut()
|
||||
.append_pair("apikey", &self.client_id)
|
||||
.append_pair("nonce", &format!("{}", nonce))
|
||||
.append_pair("timestamp", &format!("{}", timestamp));
|
||||
|
||||
// create signature
|
||||
let mut hmac = Hmac::<Sha256>::new_from_slice(&self.client_secret.secret().as_bytes())
|
||||
.expect("HMAC can take key of any size");
|
||||
hmac.update(method.as_str().as_bytes());
|
||||
hmac.update(&[b'\0']);
|
||||
hmac.update(url.as_str().as_bytes());
|
||||
hmac.update(&[b'\0']);
|
||||
hmac.update(body);
|
||||
let signature: String = hmac.finalize().into_bytes().encode_hex();
|
||||
|
||||
url.query_pairs_mut().append_pair("signature", &signature);
|
||||
|
||||
url
|
||||
}
|
||||
}
|
||||
152
zeroidc/vendor/oauth2/examples/msgraph.rs
vendored
Normal file
152
zeroidc/vendor/oauth2/examples/msgraph.rs
vendored
Normal file
@@ -0,0 +1,152 @@
|
||||
//!
|
||||
//! This example showcases the Microsoft Graph OAuth2 process for requesting access to Microsoft
|
||||
//! services using PKCE.
|
||||
//!
|
||||
//! Before running it, you'll need to generate your own Microsoft OAuth2 credentials. See
|
||||
//! https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app
|
||||
//! * Register a `Web` application with a `Redirect URI` of `http://localhost:3003/redirect`.
|
||||
//! * In the left menu select `Overview`. Copy the `Application (client) ID` as the MSGRAPH_CLIENT_ID.
|
||||
//! * In the left menu select `Certificates & secrets` and add a new client secret. Copy the secret value
|
||||
//! as MSGRAPH_CLIENT_SECRET.
|
||||
//! * In the left menu select `API permissions` and add a permission. Select Microsoft Graph and
|
||||
//! `Delegated permissions`. Add the `Files.Read` permission.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! MSGRAPH_CLIENT_ID=xxx MSGRAPH_CLIENT_SECRET=yyy cargo run --example msgraph
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::basic::BasicClient;
|
||||
// Alternatively, this can be `oauth2::curl::http_client` or a custom client.
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::{
|
||||
AuthType, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge,
|
||||
RedirectUrl, Scope, TokenUrl,
|
||||
};
|
||||
use std::env;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
fn main() {
|
||||
let graph_client_id = ClientId::new(
|
||||
env::var("MSGRAPH_CLIENT_ID").expect("Missing the MSGRAPH_CLIENT_ID environment variable."),
|
||||
);
|
||||
let graph_client_secret = ClientSecret::new(
|
||||
env::var("MSGRAPH_CLIENT_SECRET")
|
||||
.expect("Missing the MSGRAPH_CLIENT_SECRET environment variable."),
|
||||
);
|
||||
let auth_url =
|
||||
AuthUrl::new("https://login.microsoftonline.com/common/oauth2/v2.0/authorize".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url =
|
||||
TokenUrl::new("https://login.microsoftonline.com/common/oauth2/v2.0/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
|
||||
// Set up the config for the Microsoft Graph OAuth2 process.
|
||||
let client = BasicClient::new(
|
||||
graph_client_id,
|
||||
Some(graph_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
// Microsoft Graph requires client_id and client_secret in URL rather than
|
||||
// using Basic authentication.
|
||||
.set_auth_type(AuthType::RequestBody)
|
||||
// This example will be running its own server at localhost:3003.
|
||||
// See below for the server implementation.
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new("http://localhost:3003/redirect".to_string())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
|
||||
// Microsoft Graph supports Proof Key for Code Exchange (PKCE - https://oauth.net/2/pkce/).
|
||||
// Create a PKCE code verifier and SHA-256 encode it as a code challenge.
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
// Generate the authorization URL to which we'll redirect the user.
|
||||
let (authorize_url, csrf_state) = client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
// This example requests read access to OneDrive.
|
||||
.add_scope(Scope::new(
|
||||
"https://graph.microsoft.com/Files.Read".to_string(),
|
||||
))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\n",
|
||||
authorize_url.to_string()
|
||||
);
|
||||
|
||||
// A very naive implementation of the redirect server.
|
||||
let listener = TcpListener::bind("127.0.0.1:3003").unwrap();
|
||||
for stream in listener.incoming() {
|
||||
if let Ok(mut stream) = stream {
|
||||
let code;
|
||||
let state;
|
||||
{
|
||||
let mut reader = BufReader::new(&stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line).unwrap();
|
||||
|
||||
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
|
||||
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
|
||||
|
||||
let code_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "code"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = code_pair;
|
||||
code = AuthorizationCode::new(value.into_owned());
|
||||
|
||||
let state_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "state"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = state_pair;
|
||||
state = CsrfToken::new(value.into_owned());
|
||||
}
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
message
|
||||
);
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
|
||||
println!("MS Graph returned the following code:\n{}\n", code.secret());
|
||||
println!(
|
||||
"MS Graph returned the following state:\n{} (expected `{}`)\n",
|
||||
state.secret(),
|
||||
csrf_state.secret()
|
||||
);
|
||||
|
||||
// Exchange the code with a token.
|
||||
let token = client
|
||||
.exchange_code(code)
|
||||
// Send the PKCE code verifier in the token request
|
||||
.set_pkce_verifier(pkce_code_verifier)
|
||||
.request(http_client);
|
||||
|
||||
println!("MS Graph returned the following token:\n{:?}\n", token);
|
||||
|
||||
// The server will terminate itself after collecting the first code.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
246
zeroidc/vendor/oauth2/examples/wunderlist.rs
vendored
Normal file
246
zeroidc/vendor/oauth2/examples/wunderlist.rs
vendored
Normal file
@@ -0,0 +1,246 @@
|
||||
//!
|
||||
//! This example showcases the Wunderlist OAuth2 process for requesting access to the user's todo lists.
|
||||
//! Wunderlist does not implement the correct token response, so this serves as an example of how to
|
||||
//! implement a custom client.
|
||||
//!
|
||||
//! Before running it, you'll need to create your own wunderlist app.
|
||||
//!
|
||||
//! In order to run the example call:
|
||||
//!
|
||||
//! ```sh
|
||||
//! WUNDER_CLIENT_ID=xxx WUNDER_CLIENT_SECRET=yyy cargo run --example wunderlist
|
||||
//! ```
|
||||
//!
|
||||
//! ...and follow the instructions.
|
||||
//!
|
||||
|
||||
use oauth2::TokenType;
|
||||
use oauth2::{
|
||||
basic::{
|
||||
BasicErrorResponse, BasicRevocationErrorResponse, BasicTokenIntrospectionResponse,
|
||||
BasicTokenType,
|
||||
},
|
||||
revocation::StandardRevocableToken,
|
||||
};
|
||||
// Alternatively, this can be `oauth2::curl::http_client` or a custom client.
|
||||
use oauth2::helpers;
|
||||
use oauth2::reqwest::http_client;
|
||||
use oauth2::{
|
||||
AccessToken, AuthUrl, AuthorizationCode, Client, ClientId, ClientSecret, CsrfToken,
|
||||
EmptyExtraTokenFields, ExtraTokenFields, RedirectUrl, RefreshToken, Scope, TokenResponse,
|
||||
TokenUrl,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
|
||||
use std::env;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use url::Url;
|
||||
|
||||
type SpecialTokenResponse = NonStandardTokenResponse<EmptyExtraTokenFields>;
|
||||
type SpecialClient = Client<
|
||||
BasicErrorResponse,
|
||||
SpecialTokenResponse,
|
||||
BasicTokenType,
|
||||
BasicTokenIntrospectionResponse,
|
||||
StandardRevocableToken,
|
||||
BasicRevocationErrorResponse,
|
||||
>;
|
||||
|
||||
fn default_token_type() -> Option<BasicTokenType> {
|
||||
Some(BasicTokenType::Bearer)
|
||||
}
|
||||
|
||||
///
|
||||
/// Non Standard OAuth2 token response.
|
||||
///
|
||||
/// This struct includes the fields defined in
|
||||
/// [Section 5.1 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.1), as well as
|
||||
/// extensions defined by the `EF` type parameter.
|
||||
/// In this particular example token_type is optional to showcase how to deal with a non
|
||||
/// compliant provider.
|
||||
///
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
pub struct NonStandardTokenResponse<EF: ExtraTokenFields> {
|
||||
access_token: AccessToken,
|
||||
// In this example wunderlist does not follow the RFC specs and don't return the
|
||||
// token_type. `NonStandardTokenResponse` makes the `token_type` optional.
|
||||
#[serde(default = "default_token_type")]
|
||||
token_type: Option<BasicTokenType>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
expires_in: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
refresh_token: Option<RefreshToken>,
|
||||
#[serde(rename = "scope")]
|
||||
#[serde(deserialize_with = "helpers::deserialize_space_delimited_vec")]
|
||||
#[serde(serialize_with = "helpers::serialize_space_delimited_vec")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
scopes: Option<Vec<Scope>>,
|
||||
|
||||
#[serde(bound = "EF: ExtraTokenFields")]
|
||||
#[serde(flatten)]
|
||||
extra_fields: EF,
|
||||
}
|
||||
|
||||
impl<EF> TokenResponse<BasicTokenType> for NonStandardTokenResponse<EF>
|
||||
where
|
||||
EF: ExtraTokenFields,
|
||||
BasicTokenType: TokenType,
|
||||
{
|
||||
///
|
||||
/// REQUIRED. The access token issued by the authorization server.
|
||||
///
|
||||
fn access_token(&self) -> &AccessToken {
|
||||
&self.access_token
|
||||
}
|
||||
///
|
||||
/// REQUIRED. The type of the token issued as described in
|
||||
/// [Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1).
|
||||
/// Value is case insensitive and deserialized to the generic `TokenType` parameter.
|
||||
/// But in this particular case as the service is non compliant, it has a default value
|
||||
///
|
||||
fn token_type(&self) -> &BasicTokenType {
|
||||
match &self.token_type {
|
||||
Some(t) => t,
|
||||
None => &BasicTokenType::Bearer,
|
||||
}
|
||||
}
|
||||
///
|
||||
/// RECOMMENDED. The lifetime in seconds of the access token. For example, the value 3600
|
||||
/// denotes that the access token will expire in one hour from the time the response was
|
||||
/// generated. If omitted, the authorization server SHOULD provide the expiration time via
|
||||
/// other means or document the default value.
|
||||
///
|
||||
fn expires_in(&self) -> Option<Duration> {
|
||||
self.expires_in.map(Duration::from_secs)
|
||||
}
|
||||
///
|
||||
/// OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same
|
||||
/// authorization grant as described in
|
||||
/// [Section 6](https://tools.ietf.org/html/rfc6749#section-6).
|
||||
///
|
||||
fn refresh_token(&self) -> Option<&RefreshToken> {
|
||||
self.refresh_token.as_ref()
|
||||
}
|
||||
///
|
||||
/// OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The
|
||||
/// scipe of the access token as described by
|
||||
/// [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). If included in the response,
|
||||
/// this space-delimited field is parsed into a `Vec` of individual scopes. If omitted from
|
||||
/// the response, this field is `None`.
|
||||
///
|
||||
fn scopes(&self) -> Option<&Vec<Scope>> {
|
||||
self.scopes.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let client_id_str = env::var("WUNDERLIST_CLIENT_ID")
|
||||
.expect("Missing the WUNDERLIST_CLIENT_ID environment variable.");
|
||||
|
||||
let client_secret_str = env::var("WUNDERLIST_CLIENT_SECRET")
|
||||
.expect("Missing the WUNDERLIST_CLIENT_SECRET environment variable.");
|
||||
|
||||
let wunder_client_id = ClientId::new(client_id_str.clone());
|
||||
let wunderlist_client_secret = ClientSecret::new(client_secret_str.clone());
|
||||
let auth_url = AuthUrl::new("https://www.wunderlist.com/oauth/authorize".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://www.wunderlist.com/oauth/access_token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
|
||||
// Set up the config for the Wunderlist OAuth2 process.
|
||||
let client = SpecialClient::new(
|
||||
wunder_client_id,
|
||||
Some(wunderlist_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
// This example will be running its own server at localhost:8080.
|
||||
// See below for the server implementation.
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new("http://localhost:8080".to_string()).expect("Invalid redirect URL"),
|
||||
);
|
||||
|
||||
// Generate the authorization URL to which we'll redirect the user.
|
||||
let (authorize_url, csrf_state) = client.authorize_url(CsrfToken::new_random).url();
|
||||
|
||||
println!(
|
||||
"Open this URL in your browser:\n{}\n",
|
||||
authorize_url.to_string()
|
||||
);
|
||||
|
||||
// A very naive implementation of the redirect server.
|
||||
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
|
||||
for stream in listener.incoming() {
|
||||
if let Ok(mut stream) = stream {
|
||||
let code;
|
||||
let state;
|
||||
{
|
||||
let mut reader = BufReader::new(&stream);
|
||||
|
||||
let mut request_line = String::new();
|
||||
reader.read_line(&mut request_line).unwrap();
|
||||
|
||||
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
|
||||
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
|
||||
|
||||
let code_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "code"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = code_pair;
|
||||
code = AuthorizationCode::new(value.into_owned());
|
||||
|
||||
let state_pair = url
|
||||
.query_pairs()
|
||||
.find(|pair| {
|
||||
let &(ref key, _) = pair;
|
||||
key == "state"
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let (_, value) = state_pair;
|
||||
state = CsrfToken::new(value.into_owned());
|
||||
}
|
||||
|
||||
let message = "Go back to your terminal :)";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{}",
|
||||
message.len(),
|
||||
message
|
||||
);
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
|
||||
println!(
|
||||
"Wunderlist returned the following code:\n{}\n",
|
||||
code.secret()
|
||||
);
|
||||
println!(
|
||||
"Wunderlist returned the following state:\n{} (expected `{}`)\n",
|
||||
state.secret(),
|
||||
csrf_state.secret()
|
||||
);
|
||||
|
||||
// Exchange the code with a token.
|
||||
let token_res = client
|
||||
.exchange_code(code)
|
||||
.add_extra_param("client_id", client_id_str)
|
||||
.add_extra_param("client_secret", client_secret_str)
|
||||
.request(http_client);
|
||||
|
||||
println!(
|
||||
"Wunderlist returned the following token:\n{:?}\n",
|
||||
token_res
|
||||
);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user