title: How to decode a cookie from the header of a websocket connection handshake? (Ruby)
body: <p>I am running a <code>Sinatra</code> app within an <code>EventMachine.run</code> loop and in my <code>ws.onopen</code> method I wish to check the <code>handshake</code> header's cookie to ensure that the incoming request is coming from a registered user of my webapp.</p>
  
  <p>My <code>Sinatra</code> app includes the following:</p>
  
  <pre><code>use Rack::Session::Cookie,  :key =&gt; COOKIE_KEY,
                              :path =&gt; '/',
                              :expire_after =&gt; 2592000, #30 days
                              :secret =&gt; COOKIE_SECRET
  </code></pre>
  
  <p>and my <code>ws.onopen</code> method looks like this (trimmed)</p>
  
  <pre><code>ws.onopen { |handshake|
    cookie, bakesale = handshake.headers['Cookie'].split('=')
    rack_cookie = Rack::Session::Cookie.new(MyApp, {
      :key =&gt; COOKIE_KEY,
      :path =&gt; '/',
      :expire_after =&gt; 2592000, #30 days
      :secret =&gt; COOKIE_SECRET
    })
    decoded = rack_cookie.coder.decode(bakesale)
    puts "decoded: #{decoded}"
  
  }
  </code></pre>
  
  <p>The value of <code>cookie</code> matches my <code>COOKIE_KEY</code> just fine, however the value of <code>decoded</code> is <code>nil</code></p>
  
  <p>How should I decode the incoming cookie data?</p>
  
  <p>-- some time later --</p>
  
  <p>I've changed the above slightly to </p>
  
  <pre><code>ws.onopen { |handshake|
    cookie, bakesale = handshake.headers['Cookie'].split('=')
    rack_cookie = Rack::Session::Cookie.new(MyApp, {
      :key =&gt; COOKIE_KEY,
      :path =&gt; '/',
      :expire_after =&gt; 2592000, #30 days
      :secret =&gt; COOKIE_SECRET,
      :coder =&gt; Rack::Session::Cookie::Base64.new
    })
  
    puts rack_cookie.coder.decode(bakesale)
  
  }
  </code></pre>
  
  <p>and that outputs</p>
  
  <p><code>?q?[?????ov??????to?Z???294cb6e2b95e9?##v3???#c&amp;F3#SC?CSC#CSs?c3sSCCs?cCm;FI"__FLASH__;F{I"   user;FU:Moped::BSO?㣤?&amp;?V7D?B!</code></p>
  
  <p>which looks like it needs marshalling.</p>
  
  <p>However <code>Marshal.load (rack_cookie.coder.decode(bakesale))</code> throws an exception, saying <code>dump format error for symbol(0x10)</code></p>
  
  <p>-- and even more time later --</p>
  
  <p>I also tried <code>rack_cookie.coder.decode(bakesale.split('--').first)</code></p>
  
  <p>which resulted in</p>
  
  <p><code>??H?d????=?d:ETI"E7ce599b294cb6e2b95e9?##v3???#c&amp;F3#SC?CSC#CSs?c3sSCCs?cCm;FI"__FLASH__;F{I" user;FU:Moped::BSO?㣤?&amp;?V7D?B!</code></p>
  
  <p>So as you can see, there is a minor difference, but either way I need to somehow turn that into a valid hash.</p>
  
  <p>Marshal.load(rack_cookie.coder.decode(bakesale.split('--').first)) still results in <code>dump format error for symbol(0x10)</code> either way.</p>
  
  <p>So I feel I'm closer, but no cigar as yet.</p>