Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active September 11, 2022 22:15
Show Gist options
  • Save Porges/83ad8305fb5053e489624d62eaf07a81 to your computer and use it in GitHub Desktop.
Save Porges/83ad8305fb5053e489624d62eaf07a81 to your computer and use it in GitHub Desktop.
#[tokio::main]
pub async fn login() -> Result<()> {
println!("Loggin In");
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let tx = Arc::new(Mutex::new(Some(tx)));
// If this is not the first time you are using the client credentials grant
// then you only have to run request_access_token() and you can comment out
// what is below.
let query = warp::query::<AccessCode>()
.map(Some)
.or_else(|_| async { Ok::<(Option<AccessCode>,), std::convert::Infallible>((None,)) });
let routes = warp::get().and(warp::path("redirect")).and(query).map(
move |cc: Option<AccessCode>| {
if let Some(tx) = tx.lock().unwrap().take() {
match cc {
Some(access_code) => {
// Print out for debugging purposes.
println!("CODE: {:#?}", access_code.code);
let mut file = File::create("./.code").unwrap();
writeln!(&mut file, "{}", access_code.code).unwrap();
// Request an access token.
// set_and_req_access_code(access_code);
// Generic login page response.
// Response::builder().body(String::from(
// "Successfully Logged In! You can close your browser.",
// ))
_ = tx.send(()); // ignore error if recvr has been dropped
Ok(warp::reply::with_status("Hello from <b>tdi</b> - the access code was received and stored locally, you may safely close this browser window!", http::status::StatusCode::CREATED))
}
None => {
_ = tx.send(()); // ignore error if recvr has been dropped
//Response::builder().body(String::from("There was an issue getting the access code."))
Ok(warp::reply::with_status("Hello from <b>tdi</b> - error encountered requesting the access code.", http::status::StatusCode::NOT_FOUND))
},
}
} else {
Ok(warp::reply::with_status("Already received request", http::status::StatusCode::BAD_REQUEST))
}
},
);
// Get the oauth client and request a browser sign in
let mut oauth = get_oauth_client("code");
let mut request = oauth.build().code_flow();
request.browser_authorization().open().unwrap();
//warp::serve(routes).run(([127, 0, 0, 1], 8000)).await;
println!("Spawning server, awaiting access code.");
let (_, server) =
warp::serve(routes).bind_with_graceful_shutdown(([127, 0, 0, 1], 8000), async move {
_ = rx.await; // ignore error if sender disappeared
});
println!("waiting for result");
server.await;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment