Skip to content

Commit

Permalink
simplified logic and code quality in decode
Browse files Browse the repository at this point in the history
  • Loading branch information
ab320012 committed May 4, 2018
1 parent aea6da4 commit 0014e93
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
2 changes: 2 additions & 0 deletions lib/jwt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ def decode(jwt, key = nil, verify = true, options = {}, &keyfinder)

[@payload, @header]
end

private_class_method

def verify_signature(&keyfinder)
@key = find_key(&keyfinder) if keyfinder

Expand Down
48 changes: 34 additions & 14 deletions lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,53 @@ def self.base64url_decode(str)

def initialize(jwt, verify)
@jwt = jwt
@segments = jwt.split('.')
@verify = verify
@header = ''
@payload = ''
@signature = ''
end

def decode_segments
header_segment, payload_segment, crypto_segment = raw_segments
@header, @payload = decode_header_and_payload(header_segment, payload_segment)
@signature = Decode.base64url_decode(crypto_segment.to_s) if @verify
signing_input = [header_segment, payload_segment].join('.')
[@header, @payload, @signature, signing_input]
validate_segment_count
decode_crypto if @verify
return_values
end

private

def raw_segments
segments = @jwt.split('.')
required_num_segments = @verify ? [3] : [2, 3]
raise(JWT::DecodeError, 'Not enough or too many segments') unless required_num_segments.include? segments.length
segments
def validate_segment_count
raise(JWT::DecodeError, 'Not enough or too many segments') unless
(@verify && segment_length != 3) ||
(segment_length != 3 || segment_length != 2)
end

def decode_header_and_payload(header_segment, payload_segment)
header = JSON.parse(Decode.base64url_decode(header_segment))
payload = JSON.parse(Decode.base64url_decode(payload_segment))
[header, payload]
def segment_length
@segments.count
end

def decode_crypto
@signature = Decode.base64url_decode(@segments[2])
end

def return_values
[header, payload, @signature, signing_input]
end

def header
parse_and_decode @segments[0]
end

def payload
parse_and_decode @segments[1]
end

def signing_input
@segments.first(2).join('.')
end

def parse_and_decode(segment)
JSON.parse(Decode.base64url_decode(segment))
rescue JSON::ParserError
raise JWT::DecodeError, 'Invalid segment encoding'
end
Expand Down

0 comments on commit 0014e93

Please sign in to comment.