Skip to content

Commit

Permalink
Address clippy lints and clean up examples
Browse files Browse the repository at this point in the history
  • Loading branch information
ramosbugs committed Feb 21, 2024
1 parent 8bd0ff1 commit d675e81
Show file tree
Hide file tree
Showing 12 changed files with 344 additions and 414 deletions.
149 changes: 67 additions & 82 deletions examples/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@
//!
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 url::Url;

use std::env;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use url::Url;

fn main() {
let github_client_id = ClientId::new(
Expand Down Expand Up @@ -60,88 +60,73 @@ fn main() {
.add_scope(Scope::new("user:email".to_string()))
.url();

println!("Open this URL in your browser:\n{authorize_url}\n");

let (code, state) = {
// A very naive implementation of the redirect server.
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

// The server will terminate itself after collecting the first code.
let Some(mut stream) = listener.incoming().flatten().next() else {
panic!("listener terminated without accepting a connection");
};

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 = url
.query_pairs()
.find(|(key, _)| key == "code")
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
.unwrap();

let state = url
.query_pairs()
.find(|(key, _)| key == "state")
.map(|(_, state)| CsrfToken::new(state.into_owned()))
.unwrap();

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();

(code, state)
};

println!("Github returned the following code:\n{}\n", code.secret());
println!(
"Open this URL in your browser:\n{}\n",
authorize_url.to_string()
"Github returned the following state:\n{} (expected `{}`)\n",
state.secret(),
csrf_state.secret()
);

// 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;
}
// 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()
.flat_map(|comma_separated| comma_separated.split(','))
.collect::<Vec<_>>()
} else {
Vec::new()
};
println!("Github returned the following scopes:\n{:?}\n", scopes);
}
}
125 changes: 55 additions & 70 deletions examples/github_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@
//!
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;

use std::env;

#[tokio::main]
async fn main() {
let github_client_id = ClientId::new(
Expand Down Expand Up @@ -61,18 +61,14 @@ async fn main() {
.add_scope(Scope::new("user:email".to_string()))
.url();

println!(
"Open this URL in your browser:\n{}\n",
authorize_url.to_string()
);
println!("Open this URL in your browser:\n{authorize_url}\n");

let (code, state) = {
// A very naive implementation of the redirect server.
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();

// 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;
{
loop {
if let Ok((mut stream, _)) = listener.accept().await {
let mut reader = BufReader::new(&mut stream);

let mut request_line = String::new();
Expand All @@ -81,71 +77,60 @@ async fn main() {
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
let code = url
.query_pairs()
.find(|pair| {
let &(ref key, _) = pair;
key == "code"
})
.find(|(key, _)| key == "code")
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
.unwrap();

let (_, value) = code_pair;
code = AuthorizationCode::new(value.into_owned());

let state_pair = url
let state = url
.query_pairs()
.find(|pair| {
let &(ref key, _) = pair;
key == "state"
})
.find(|(key, _)| key == "state")
.map(|(_, state)| CsrfToken::new(state.into_owned()))
.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();

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 (code, state);
}

// The server will terminate itself after collecting the first code.
break;
}
};

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()
.flat_map(|comma_separated| comma_separated.split(','))
.collect::<Vec<_>>()
} else {
Vec::new()
};
println!("Github returned the following scopes:\n{:?}\n", scopes);
}
}
Loading

0 comments on commit d675e81

Please sign in to comment.