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 b76e76b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
1 change: 1 addition & 0 deletions lib/jwt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ 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
46 changes: 32 additions & 14 deletions lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +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
private
def validate_segment_count
raise(JWT::DecodeError, 'Not enough or too many segments') unless
(@verify and @segments.length != 3) ||
(@segments.length != 3 or @segments.length != 2)
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 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 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

end
end

0 comments on commit b76e76b

Please sign in to comment.