Merge branch 'access-token'

Merges in the access token fixes into main.
This commit is contained in:
2024-12-16 20:00:40 -05:00
2 changed files with 40 additions and 11 deletions

View File

@@ -1,20 +1,31 @@
use std::error::Error; use std::error::Error;
use std::fs::read_to_string; use std::fs::read_to_string;
use oauth2::basic::BasicClient;
use oauth2::reqwest::http_client;
use oauth2::AccessToken;
use oauth2::AuthUrl;
use oauth2::ClientId;
use oauth2::ClientSecret;
use oauth2::TokenResponse;
use oauth2::TokenUrl;
mod types;
use types::ClientAuth;
pub fn run() -> Result<(), Box<dyn Error>> { pub fn run() -> Result<(), Box<dyn Error>> {
let client_auth = read_client_auth()?; let client_auth = read_client_auth()?;
println!("Client ID: {}", client_auth.client_id); println!("Client ID: {}", client_auth.id);
println!("Client Secret: {}", client_auth.client_secret); println!("Client Secret: {}", client_auth.secret);
let access_token = get_api_token(client_auth.id, client_auth.secret)?;
println!("Access Token: {access_token:#?}");
Ok(()) Ok(())
} }
struct ClientAuth {
client_id: String,
client_secret: String,
}
fn read_client_auth() -> Result<ClientAuth, Box<dyn Error>> { fn read_client_auth() -> Result<ClientAuth, Box<dyn Error>> {
let mut id = String::new(); let mut id = String::new();
let mut secret = String::new(); let mut secret = String::new();
@@ -29,8 +40,22 @@ fn read_client_auth() -> Result<ClientAuth, Box<dyn Error>> {
} }
} }
Ok(ClientAuth { Ok(ClientAuth { id, secret })
client_id: id, }
client_secret: secret,
}) fn get_api_token(client_id: String, client_secret: String) -> Result<AccessToken, Box<dyn Error>> {
let client = BasicClient::new(
ClientId::new(client_id),
Some(ClientSecret::new(client_secret)),
AuthUrl::new("https://api.tailscale.com/api/v2/oauth/token".to_string())?,
Some(TokenUrl::new(
"https://api.tailscale.com/api/v2/oauth/token".to_string(),
)?),
);
let token_result = client.exchange_client_credentials().request(http_client)?;
let access_token = token_result.access_token().to_owned();
Ok(access_token)
} }

4
src/types.rs Normal file
View File

@@ -0,0 +1,4 @@
pub struct ClientAuth {
pub id: String,
pub secret: String,
}