Skip to content

Commit 6f46c7a

Browse files
committed
oauth: break-out code parsing
1 parent 961797a commit 6f46c7a

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

oauth/src/lib.rs

+14-9
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,23 @@ use std::{
1313
};
1414
use url::Url;
1515

16+
fn get_code(redirect_url: &str) -> AuthorizationCode {
17+
let url = Url::parse(redirect_url).unwrap();
18+
let code = url
19+
.query_pairs()
20+
.find(|(key, _)| key == "code")
21+
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
22+
.unwrap();
23+
code
24+
}
25+
1626
fn get_authcode_stdin() -> AuthorizationCode {
17-
println!("Provide code");
27+
println!("Provide redirect URL");
1828
let mut buffer = String::new();
1929
let stdin = io::stdin(); // We get `Stdin` here.
2030
stdin.read_line(&mut buffer).unwrap();
2131

22-
AuthorizationCode::new(buffer.trim().into())
32+
get_code(buffer.trim())
2333
}
2434

2535
fn get_authcode_listener(socket_address: SocketAddr) -> AuthorizationCode {
@@ -39,13 +49,7 @@ fn get_authcode_listener(socket_address: SocketAddr) -> AuthorizationCode {
3949
reader.read_line(&mut request_line).unwrap();
4050

4151
let redirect_url = request_line.split_whitespace().nth(1).unwrap();
42-
let url = Url::parse(&("http://localhost".to_string() + redirect_url)).unwrap();
43-
44-
let code = url
45-
.query_pairs()
46-
.find(|(key, _)| key == "code")
47-
.map(|(_, code)| AuthorizationCode::new(code.into_owned()))
48-
.unwrap();
52+
let code = get_code(&("http://localhost".to_string() + redirect_url));
4953

5054
let message = "Go back to your terminal :)";
5155
let response = format!(
@@ -60,6 +64,7 @@ fn get_authcode_listener(socket_address: SocketAddr) -> AuthorizationCode {
6064

6165
// TODO: Return a Result?
6266
// TODO: Pass in redirect_address instead since the redirect host depends on client ID?
67+
// TODO: Pass in scopes.
6368
pub fn get_access_token(client_id: &str, redirect_port: u16) -> String {
6469
// Must use host 127.0.0.1 with Spotify Desktop client ID.
6570
let redirect_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), redirect_port);

0 commit comments

Comments
 (0)