Add create-api-key sub-command.

This makes is possible to create a global API key (programmatically)
using the CLI.

Fixes https://github.com/chirpstack/chirpstack-rest-api/issues/12.
This commit is contained in:
Orne Brocaar 2023-07-13 11:10:32 +01:00
parent 9d543603d5
commit a975cf3223
3 changed files with 46 additions and 19 deletions

View File

@ -0,0 +1,25 @@
use anyhow::Result;
use crate::api::auth::claims;
use crate::config;
use crate::storage::api_key;
pub async fn run(name: &str) -> Result<()> {
let conf = config::get();
crate::storage::setup().await?;
let key = api_key::create(api_key::ApiKey {
name: name.to_string(),
is_admin: true,
..Default::default()
})
.await?;
let token = claims::AuthClaim::new_for_api_key(&key.id).encode(conf.api.secret.as_ref())?;
println!("id: {}", key.id);
println!("token: {}", token);
Ok(())
}

View File

@ -1,4 +1,5 @@
pub mod configfile; pub mod configfile;
pub mod create_api_key;
pub mod import_legacy_lorawan_devices_repository; pub mod import_legacy_lorawan_devices_repository;
pub mod print_ds; pub mod print_ds;
pub mod root; pub mod root;

View File

@ -14,7 +14,6 @@ extern crate diesel;
extern crate anyhow; extern crate anyhow;
use std::path::Path; use std::path::Path;
use std::process;
use std::str::FromStr; use std::str::FromStr;
use anyhow::Result; use anyhow::Result;
@ -78,6 +77,13 @@ enum Commands {
#[arg(short, long, value_name = "DIR")] #[arg(short, long, value_name = "DIR")]
dir: String, dir: String,
}, },
/// Create global API key.
CreateApiKey {
/// Name.
#[arg(short, long, value_name = "NAME")]
name: String,
},
} }
#[tokio::main] #[tokio::main]
@ -104,25 +110,20 @@ async fn main() -> Result<()> {
.init(); .init();
} }
if let Some(Commands::Configfile {}) = &cli.command { match &cli.command {
cmd::configfile::run(); Some(Commands::Configfile {}) => cmd::configfile::run(),
process::exit(0); Some(Commands::PrintDs { dev_eui }) => {
let dev_eui = EUI64::from_str(dev_eui).unwrap();
cmd::print_ds::run(&dev_eui).await.unwrap();
}
Some(Commands::ImportLegacyLorawanDevicesRepository { dir }) => {
cmd::import_legacy_lorawan_devices_repository::run(Path::new(&dir))
.await
.unwrap()
}
Some(Commands::CreateApiKey { name }) => cmd::create_api_key::run(&name).await?,
None => cmd::root::run().await?,
} }
if let Some(Commands::PrintDs { dev_eui }) = &cli.command {
let dev_eui = EUI64::from_str(dev_eui).unwrap();
cmd::print_ds::run(&dev_eui).await.unwrap();
process::exit(0);
}
if let Some(Commands::ImportLegacyLorawanDevicesRepository { dir }) = &cli.command {
cmd::import_legacy_lorawan_devices_repository::run(Path::new(&dir))
.await
.unwrap();
process::exit(0);
}
cmd::root::run().await?;
Ok(()) Ok(())
} }