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

Add a whoami command to display the logged in user #4625

Closed
wants to merge 1 commit into from
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
1 change: 1 addition & 0 deletions src/bin/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ macro_rules! each_subcommand{
$mac!(update);
$mac!(verify_project);
$mac!(version);
$mac!(whoami);
$mac!(yank);
}
}
Expand Down
51 changes: 51 additions & 0 deletions src/bin/whoami.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use cargo::ops;
use cargo::util::{CliResult, Config};

#[derive(Deserialize)]
pub struct Options {
flag_index: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
}

pub const USAGE: &'static str = "
Check if an api token exists locally and who it belongs to

Usage:
cargo whoami [options] [<token>]

Options:
-h, --help Print this message
--index INDEX Registry index to search in
-v, --verbose ... Use verbose output (-vv very verbose/build.rs output)
-q, --quiet No output printed to stdout
--color WHEN Coloring: auto, always, never
--frozen Require Cargo.lock and cache are up to date
--locked Require Cargo.lock is up to date
-Z FLAG ... Unstable (nightly-only) flags to Cargo

";

pub fn execute(options: Options, config: &mut Config) -> CliResult {
config.configure(
options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&options.flag_z,
)?;

let Options {
flag_index: index,
..
} = options;

ops::registry_whoami(config, index)?;
Ok(())
}
2 changes: 1 addition & 1 deletion src/cargo/ops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub use self::lockfile::{load_pkg_lockfile, write_pkg_lockfile};
pub use self::cargo_test::{run_tests, run_benches, TestOptions};
pub use self::cargo_package::{package, PackageOpts};
pub use self::registry::{publish, registry_configuration, RegistryConfig};
pub use self::registry::{registry_login, search, http_proxy_exists, http_handle};
pub use self::registry::{registry_login, registry_whoami, search, http_proxy_exists, http_handle};
pub use self::registry::{modify_owners, yank, OwnersOptions, PublishOpts};
pub use self::cargo_fetch::fetch;
pub use self::cargo_pkgid::pkgid;
Expand Down
12 changes: 12 additions & 0 deletions src/cargo/ops/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,18 @@ pub fn registry_login(config: &Config, token: String) -> CargoResult<()> {
config::save_credentials(config, token)
}

pub fn registry_whoami(config: &Config, index: Option<String>) -> CargoResult<()> {
let RegistryConfig { token, .. } = registry_configuration(config)?;
let (mut registry, _) = registry(config, token.clone(), index)?;

match registry.whoami() {
Ok(user) => config.shell().status("Whoami", format!("Currently logged in as `{}`", user.login))?,
Copy link
Contributor

@lukaslueg lukaslueg Oct 26, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this wording is optimal. "Currently logged in as", given to a web-accustomed audience, sounds like the status of a temporary session. We could also be more clear about where this user is actually used.

FWIW "Crates will be published/yanked by user `{}`"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lukaslueg I get where you're coming from, and normally I'd agree. Two things are hanging me up though. The first is that users already establish local credentials by running cargo login (normally), so there's already some precedent there. Additionally, while publish/yank are probably the two most common commands, there's certainly more to do that requires authentication.

If you wanted to move away from logged in, maybe Authenticated as {} or Operating as {}?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest mirroring what whoami or id -un does and just print out the username, with no further formatting. This has the added benefit that the command can be used in scripts more easily, without having to do a awk-pass. That is

$ cargo whoami
leeroyjenkins

and

$ cargo whoami
[some TokenMissing-message to stderr]
$ echo $?
1

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that as well while implementing this. The main reason I didn't is because it doesn't match how the rest of cargo generally outputs info to STDOUT

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#4646 comes with a small change in config.shell() to determine if stderr is actually human-readable. One can extend that to stdout and output an unformatted string if stdout is hooked up. If wonder if this is surprising behavior, though

Err(e) => config.shell().status("Whoami", format!("{}", e))?,
};

Ok(())
}

pub struct OwnersOptions {
pub krate: Option<String>,
pub token: Option<String>,
Expand Down
10 changes: 10 additions & 0 deletions src/crates-io/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ pub struct Warnings {
}

#[derive(Deserialize)] struct R { ok: bool }
#[derive(Deserialize)] struct MeResponse { user: Option<User> }
#[derive(Deserialize)] struct OwnerResponse { ok: bool, msg: String }
#[derive(Deserialize)] struct ApiErrorList { errors: Vec<ApiError> }
#[derive(Deserialize)] struct ApiError { detail: String }
Expand Down Expand Up @@ -256,6 +257,15 @@ impl Registry {
Ok(())
}

pub fn whoami(&mut self) -> Result<User> {
let body = self.get(String::from("/me"))?;

match serde_json::from_str::<MeResponse>(&body)?.user {
Some(user) => Ok(user),
_ => Err(Error::from_kind(ErrorKind::TokenMissing))
}
}

fn put(&mut self, path: String, b: &[u8]) -> Result<String> {
self.handle.put(true)?;
self.req(path, Some(b), Auth::Authorized)
Expand Down