3

I have a URL of this format:

https://clientjiberish:clientsecretjiberish@api.example.com/users?username=tralala

when I do:

url = 'https://clientjiberish:clientsecretjiberish@api.example.com/users?username=tralala'
uri = URI(url)

I get all that I need.

uri.host => "api.example.com"
uri.userinfo => "clientjiberish:clientsecretjiberish"
uri.path => '/users'
uri.scheme => 'https'

The problem rises when the userinfo part has a forward slash in it. I have no power to change the API that serves the API keys, so I need to figure out a way to extract the mentioned parts of the URI.

Here's an example on what you can test the URI:

url = 'https://clientjiberish:client/secretjiberish@api.example.com/users?username=tralala'
uri = URI(url)

The error:

URI::InvalidURIError: bad URI(is not URI?)

I found out that you can create your own parser like this:

parser = URI::Parser.new(:RESERVED => ";/?:@&=+$,\\[\\]")
uri = parser.parse(url)

but I don't know enough about regex to make it work.

Marko Ćilimković
  • 734
  • 1
  • 8
  • 22
  • 1
    Can you not just escape forward slash in `client/secretjiberish` with `%2F`?. – Rashmirathi Sep 28 '16 at 14:48
  • @Rashmirathi How can I access it? If I do something like: escaped_url = URI.escape(url, '/') and then URI(url) I can't use any of the URI methods since they all return nil. – Marko Ćilimković Sep 28 '16 at 16:03
  • I mean only escape it in the part `clientjiberish:client/secretjiberish `, so url becomes `https://clientjiberish:client%2Fsecretjiberish@api.example.com/users?username=tralala`. – Rashmirathi Sep 28 '16 at 19:10
  • I receive a string ```'https://clientjiberish:clientsecretjiberish@api.example.com/users?username=tralala'```. How do I just escape that part of the string? – Marko Ćilimković Sep 29 '16 at 08:08

1 Answers1

0
url = 'https://clientjiberish:client/secretjiberish@api.example.com/users?username=tralala'
USER_INFO_REGEX = /\Ahttp[s]+:\/\/(.*)@.*\z/i
user_info = USER_INFO_REGEX.match(url)[1]
parsed_user_info = user_info.gsub(/\//, '%2F')
url = url.gsub(Regexp.new(user_info), parsed_user_info)
uri = URI(url)

USER_INFO_REGEX matches the string between https:// and @api.example.com.... Just escape the user info string and replace it in the url.

Kapitol
  • 133
  • 4