Skip to content

Commit

Permalink
feat(output): Output as JSON for consumption with jq
Browse files Browse the repository at this point in the history
  • Loading branch information
Corey McGregor committed Sep 21, 2018
1 parent b2e8527 commit 2f1e90a
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,26 @@ extern crate term_painter;

use chrono::{Duration, Utc};
use clap::{App, Arg, ArgMatches, SubCommand};
use jwt::{dangerous_unsafe_decode, decode, encode, Algorithm, Header, TokenData, Validation};
use jwt::errors::{Error, ErrorKind, Result as JWTResult};
use jwt::{dangerous_unsafe_decode, decode, encode, Algorithm, Header, TokenData, Validation};
use serde_json::{from_str, to_string_pretty, Value};
use std::collections::BTreeMap;
use std::process::exit;
use term_painter::ToStyle;
use term_painter::Color::*;
use term_painter::Attr::*;
use term_painter::ToStyle;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct PayloadItem(String, Value);

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Payload(BTreeMap<String, Value>);

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TokenOutput {
header: Header,
payload: Payload,
}

arg_enum!{
#[derive(Debug, PartialEq)]
enum SupportedAlgorithms {
Expand Down Expand Up @@ -109,6 +114,15 @@ impl SupportedAlgorithms {
}
}

impl TokenOutput {
fn new(data: TokenData<Payload>) -> Self {
TokenOutput {
header: data.header,
payload: data.claims,
}
}
}

fn config_options<'a, 'b>() -> App<'a, 'b> {
App::new("jwt")
.about("Encode and decode JWTs from the command line")
Expand Down Expand Up @@ -360,8 +374,6 @@ fn print_decoded_token(
validated_token: JWTResult<TokenData<Payload>>,
token_data: TokenData<Payload>,
) {
println!("\n");

match &validated_token {
&Err(Error(ref err, _)) => {
match err {
Expand Down Expand Up @@ -418,13 +430,13 @@ fn print_decoded_token(
),
};
}
_ => println!("{}", Cyan.bold().paint("Looks like a valid JWT!")),
_ => {}
}

println!("\n{}", Plain.bold().paint("Token header\n------------"));
println!("{}\n", to_string_pretty(&token_data.header).unwrap());
println!("{}", Plain.bold().paint("Token claims\n------------"));
println!("{}", to_string_pretty(&token_data.claims).unwrap());
println!(
"{}",
to_string_pretty(&TokenOutput::new(token_data)).unwrap()
);

exit(match validated_token {
Err(_) => 1,
Expand Down

0 comments on commit 2f1e90a

Please sign in to comment.