Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create credentials from access token #1098

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions core/src/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl From<AuthenticationError> for Error {
/// The credentials are used to log into the Spotify API.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Credentials {
pub username: String,
pub username: Option<String>,

#[serde(serialize_with = "serialize_protobuf_enum")]
#[serde(deserialize_with = "deserialize_protobuf_enum")]
Expand All @@ -49,19 +49,27 @@ impl Credentials {
///
/// let creds = Credentials::with_password("my account", "my password");
/// ```
pub fn with_password(username: impl Into<String>, password: impl Into<String>) -> Credentials {
Credentials {
username: username.into(),
pub fn with_password(username: impl Into<String>, password: impl Into<String>) -> Self {
Self {
username: Some(username.into()),
auth_type: AuthenticationType::AUTHENTICATION_USER_PASS,
auth_data: password.into().into_bytes(),
}
}

pub fn with_access_token(token: impl Into<String>) -> Self {
Self {
username: None,
auth_type: AuthenticationType::AUTHENTICATION_SPOTIFY_TOKEN,
auth_data: token.into().into_bytes(),
}
}

pub fn with_blob(
username: impl Into<String>,
encrypted_blob: impl AsRef<[u8]>,
device_id: impl AsRef<[u8]>,
) -> Result<Credentials, Error> {
) -> Result<Self, Error> {
fn read_u8<R: Read>(stream: &mut R) -> io::Result<u8> {
let mut data = [0u8];
stream.read_exact(&mut data)?;
Expand Down Expand Up @@ -135,10 +143,10 @@ impl Credentials {
read_u8(&mut cursor)?;
let auth_data = read_bytes(&mut cursor)?;

Ok(Credentials {
username,
auth_type,
auth_data,
Ok(Self {
username: Some(username),
auth_type: auth_type,
auth_data: auth_data,
})
}
}
Expand Down
12 changes: 7 additions & 5 deletions core/src/connection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,12 @@ pub async fn authenticate(
};

let mut packet = ClientResponseEncrypted::new();
packet
.login_credentials
.mut_or_insert_default()
.set_username(credentials.username);
if let Some(username) = credentials.username {
packet
.login_credentials
.mut_or_insert_default()
.set_username(username);
}
packet
.login_credentials
.mut_or_insert_default()
Expand Down Expand Up @@ -144,7 +146,7 @@ pub async fn authenticate(
let welcome_data = APWelcome::parse_from_bytes(data.as_ref())?;

let reusable_credentials = Credentials {
username: welcome_data.canonical_username().to_owned(),
username: Some(welcome_data.canonical_username().to_owned()),
auth_type: welcome_data.reusable_auth_credentials_type(),
auth_data: welcome_data.reusable_auth_credentials().to_owned(),
};
Expand Down
5 changes: 3 additions & 2 deletions core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,9 @@ impl Session {
}
};

info!("Authenticated as \"{}\" !", reusable_credentials.username);
self.set_username(&reusable_credentials.username);
let username = reusable_credentials.username.as_ref().expect("Username");
info!("Authenticated as \"{}\" !", username);
self.set_username(username);
if let Some(cache) = self.cache() {
if store_credentials {
cache.save_credentials(&reusable_credentials);
Expand Down
36 changes: 26 additions & 10 deletions examples/get_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,39 @@ const SCOPES: &str =

#[tokio::main]
async fn main() {
let session_config = SessionConfig::default();
let mut session_config = SessionConfig::default();

let args: Vec<_> = env::args().collect();
if args.len() != 3 {
eprintln!("Usage: {} USERNAME PASSWORD", args[0]);
if args.len() == 4 {
session_config.client_id = args[3].clone()
} else if args.len() != 3 {
eprintln!("Usage: {} USERNAME PASSWORD [CLIENT_ID]", args[0]);
return;
}
let username = &args[1];
let password = &args[2];

println!("Connecting...");
let credentials = Credentials::with_password(&args[1], &args[2]);
let session = Session::new(session_config, None);
let session = Session::new(session_config.clone(), None);
let credentials = Credentials::with_password(username, password);
println!("Connecting with password..");
let token = match session.connect(credentials, false).await {
Ok(()) => {
println!("Session username: {:#?}", session.username());
session.token_provider().get_token(SCOPES).await.unwrap()
}
Err(e) => {
println!("Error connecting: {}", e);
return;
}
};
println!("Token: {:#?}", token);

// Now create a new session with that token.
let session = Session::new(session_config, None);
let credentials = Credentials::with_access_token(token.access_token);
println!("Connecting with token..");
match session.connect(credentials, false).await {
Ok(()) => println!(
"Token: {:#?}",
session.token_provider().get_token(SCOPES).await.unwrap()
),
Ok(()) => println!("Session username: {:#?}", session.username()),
Err(e) => println!("Error connecting: {}", e),
}
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,7 @@ fn get_setup() -> Setup {
Some(Credentials::with_password(username, password))
} else {
match cached_creds {
Some(creds) if username == creds.username => Some(creds),
Some(creds) if Some(&username) == creds.username.as_ref() => Some(creds),
_ => {
let prompt = &format!("Password for {}: ", username);
match rpassword::prompt_password(prompt) {
Expand Down