|
2 | 2 |
|
3 | 3 | from __future__ import absolute_import, print_function |
4 | 4 |
|
| 5 | +import argparse |
5 | 6 | import json |
6 | | -import optparse |
7 | 7 | import sys |
8 | 8 | import time |
9 | 9 |
|
10 | | -from . import DecodeError, __package__, __version__, decode, encode |
| 10 | +from . import DecodeError, __version__, decode, encode |
11 | 11 |
|
12 | 12 |
|
13 | | -def main(): |
| 13 | +def encode_payload(args): |
| 14 | + # Try to encode |
| 15 | + if args.key is None: |
| 16 | + raise ValueError('Key is required when encoding. See --help for usage.') |
| 17 | + |
| 18 | + # Build payload object to encode |
| 19 | + payload = {} |
| 20 | + |
| 21 | + for arg in args.payload: |
| 22 | + k, v = arg.split('=', 1) |
| 23 | + |
| 24 | + # exp +offset special case? |
| 25 | + if k == 'exp' and v[0] == '+' and len(v) > 1: |
| 26 | + v = str(int(time.time()+int(v[1:]))) |
| 27 | + |
| 28 | + # Cast to integer? |
| 29 | + if v.isdigit(): |
| 30 | + v = int(v) |
| 31 | + else: |
| 32 | + # Cast to float? |
| 33 | + try: |
| 34 | + v = float(v) |
| 35 | + except ValueError: |
| 36 | + pass |
| 37 | + |
| 38 | + # Cast to true, false, or null? |
| 39 | + constants = {'true': True, 'false': False, 'null': None} |
| 40 | + |
| 41 | + if v in constants: |
| 42 | + v = constants[v] |
| 43 | + |
| 44 | + payload[k] = v |
| 45 | + |
| 46 | + token = encode( |
| 47 | + payload, |
| 48 | + key=args.key, |
| 49 | + algorithm=args.algorithm |
| 50 | + ) |
| 51 | + |
| 52 | + return token.decode('utf-8') |
| 53 | + |
| 54 | + |
| 55 | +def decode_payload(args): |
| 56 | + try: |
| 57 | + if sys.stdin.isatty(): |
| 58 | + token = sys.stdin.read() |
| 59 | + else: |
| 60 | + token = args.token |
| 61 | + |
| 62 | + token = token.encode('utf-8') |
| 63 | + data = decode(token, key=args.key, verify=args.verify) |
| 64 | + |
| 65 | + return json.dumps(data) |
| 66 | + |
| 67 | + except DecodeError as e: |
| 68 | + raise DecodeError('There was an error decoding the token: %s' % e) |
| 69 | + |
14 | 70 |
|
15 | | - usage = '''Encodes or decodes JSON Web Tokens based on input. |
| 71 | +def build_argparser(): |
16 | 72 |
|
17 | | - %prog [options] input |
| 73 | + usage = ''' |
| 74 | + Encodes or decodes JSON Web Tokens based on input. |
18 | 75 |
|
19 | | -Decoding examples: |
| 76 | + %(prog)s [options] <command> [options] input |
20 | 77 |
|
21 | | - %prog --key=secret json.web.token |
22 | | - %prog --no-verify json.web.token |
| 78 | + Decoding examples: |
23 | 79 |
|
24 | | -Encoding requires the key option and takes space separated key/value pairs |
25 | | -separated by equals (=) as input. Examples: |
| 80 | + %(prog)s --key=secret decode json.web.token |
| 81 | + %(prog)s decode --no-verify json.web.token |
26 | 82 |
|
27 | | - %prog --key=secret iss=me exp=1302049071 |
28 | | - %prog --key=secret foo=bar exp=+10 |
| 83 | + Encoding requires the key option and takes space separated key/value pairs |
| 84 | + separated by equals (=) as input. Examples: |
29 | 85 |
|
30 | | -The exp key is special and can take an offset to current Unix time.\ |
31 | | -''' |
32 | | - p = optparse.OptionParser( |
33 | | - usage=usage, |
| 86 | + %(prog)s --key=secret encode iss=me exp=1302049071 |
| 87 | + %(prog)s --key=secret encode foo=bar exp=+10 |
| 88 | +
|
| 89 | + The exp key is special and can take an offset to current Unix time. |
| 90 | + ''' |
| 91 | + |
| 92 | + arg_parser = argparse.ArgumentParser( |
34 | 93 | prog='pyjwt', |
35 | | - version='%s %s' % (__package__, __version__), |
| 94 | + usage=usage |
36 | 95 | ) |
37 | 96 |
|
38 | | - p.add_option( |
39 | | - '-n', '--no-verify', |
40 | | - action='store_false', |
41 | | - dest='verify', |
42 | | - default=True, |
43 | | - help='ignore signature and claims verification on decode' |
| 97 | + arg_parser.add_argument( |
| 98 | + '-v', '--version', |
| 99 | + action='version', |
| 100 | + version='%(prog)s ' + __version__ |
44 | 101 | ) |
45 | 102 |
|
46 | | - p.add_option( |
| 103 | + arg_parser.add_argument( |
47 | 104 | '--key', |
48 | 105 | dest='key', |
49 | 106 | metavar='KEY', |
50 | 107 | default=None, |
51 | 108 | help='set the secret key to sign with' |
52 | 109 | ) |
53 | 110 |
|
54 | | - p.add_option( |
| 111 | + arg_parser.add_argument( |
55 | 112 | '--alg', |
56 | 113 | dest='algorithm', |
57 | 114 | metavar='ALG', |
58 | 115 | default='HS256', |
59 | 116 | help='set crypto algorithm to sign with. default=HS256' |
60 | 117 | ) |
61 | 118 |
|
62 | | - options, arguments = p.parse_args() |
| 119 | + subparsers = arg_parser.add_subparsers( |
| 120 | + title='PyJWT subcommands', |
| 121 | + description='valid subcommands', |
| 122 | + help='additional help' |
| 123 | + ) |
63 | 124 |
|
64 | | - if len(arguments) > 0 or not sys.stdin.isatty(): |
65 | | - if len(arguments) == 1 and (not options.verify or options.key): |
66 | | - # Try to decode |
67 | | - try: |
68 | | - if not sys.stdin.isatty(): |
69 | | - token = sys.stdin.read() |
70 | | - else: |
71 | | - token = arguments[0] |
| 125 | + # Encode subcommand |
| 126 | + encode_parser = subparsers.add_parser('encode', help='use to encode a supplied payload') |
72 | 127 |
|
73 | | - token = token.encode('utf-8') |
74 | | - data = decode(token, key=options.key, verify=options.verify) |
| 128 | + payload_help = """Payload to encode. Must be a space separated list of key/value |
| 129 | + pairs separated by equals (=) sign.""" |
75 | 130 |
|
76 | | - print(json.dumps(data)) |
77 | | - sys.exit(0) |
78 | | - except DecodeError as e: |
79 | | - print(e) |
80 | | - sys.exit(1) |
| 131 | + encode_parser.add_argument('payload', nargs='+', help=payload_help) |
| 132 | + encode_parser.set_defaults(func=encode_payload) |
81 | 133 |
|
82 | | - # Try to encode |
83 | | - if options.key is None: |
84 | | - print('Key is required when encoding. See --help for usage.') |
85 | | - sys.exit(1) |
| 134 | + # Decode subcommand |
| 135 | + decode_parser = subparsers.add_parser('decode', help='use to decode a supplied JSON web token') |
| 136 | + decode_parser.add_argument('token', help='JSON web token to decode.') |
86 | 137 |
|
87 | | - # Build payload object to encode |
88 | | - payload = {} |
| 138 | + decode_parser.add_argument( |
| 139 | + '-n', '--no-verify', |
| 140 | + action='store_false', |
| 141 | + dest='verify', |
| 142 | + default=True, |
| 143 | + help='ignore signature and claims verification on decode' |
| 144 | + ) |
89 | 145 |
|
90 | | - for arg in arguments: |
91 | | - try: |
92 | | - k, v = arg.split('=', 1) |
| 146 | + decode_parser.set_defaults(func=decode_payload) |
| 147 | + |
| 148 | + return arg_parser |
93 | 149 |
|
94 | | - # exp +offset special case? |
95 | | - if k == 'exp' and v[0] == '+' and len(v) > 1: |
96 | | - v = str(int(time.time()+int(v[1:]))) |
97 | 150 |
|
98 | | - # Cast to integer? |
99 | | - if v.isdigit(): |
100 | | - v = int(v) |
101 | | - else: |
102 | | - # Cast to float? |
103 | | - try: |
104 | | - v = float(v) |
105 | | - except ValueError: |
106 | | - pass |
| 151 | +def main(): |
| 152 | + arg_parser = build_argparser() |
107 | 153 |
|
108 | | - # Cast to true, false, or null? |
109 | | - constants = {'true': True, 'false': False, 'null': None} |
| 154 | + try: |
| 155 | + arguments = arg_parser.parse_args(sys.argv[1:]) |
110 | 156 |
|
111 | | - if v in constants: |
112 | | - v = constants[v] |
| 157 | + output = arguments.func(arguments) |
113 | 158 |
|
114 | | - payload[k] = v |
115 | | - except ValueError: |
116 | | - print('Invalid encoding input at {}'.format(arg)) |
117 | | - sys.exit(1) |
118 | | - |
119 | | - try: |
120 | | - token = encode( |
121 | | - payload, |
122 | | - key=options.key, |
123 | | - algorithm=options.algorithm |
124 | | - ) |
125 | | - |
126 | | - print(token) |
127 | | - sys.exit(0) |
128 | | - except Exception as e: |
129 | | - print(e) |
130 | | - sys.exit(1) |
131 | | - else: |
132 | | - p.print_help() |
133 | | - |
134 | | - |
135 | | -if __name__ == '__main__': |
136 | | - main() |
| 159 | + print(output) |
| 160 | + except Exception as e: |
| 161 | + print('There was an unforseen error: ', e) |
| 162 | + arg_parser.print_help() |
0 commit comments