title: Get user from device/warden session cookie
body: <p>I need to deserialize the session cookie by hand to extract the user from it. The enviroment is rails, though it is not in the http server context, so there is no request for devise to automatically deserialise. There is the Warden::SessionSerializer, though I did not really get how to use it.</p>
  
  <p>Before I wasn't using Devise so I used this method to deserialize the rails session cookie:</p>
  
  <pre class="lang-ruby prettyprint-override"><code>def decrypt_cookie(cookie)
    cookie = CGI.unescape(cookie)
    config = Rails.application.config
  
    encrypted_cookie_salt = config.action_dispatch.encrypted_cookie_salt
    encrypted_signed_cookie_salt = config.action_dispatch.encrypted_signed_cookie_salt
  
    key_generator = ActiveSupport::KeyGenerator.new(config.secret_key_base, iterations: 1000)
    secret = key_generator.generate_key(encrypted_cookie_salt)
    sign_secret = key_generator.generate_key(encrypted_signed_cookie_salt)
  
    encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret)
    encryptor.decrypt_and_verify(cookie)
  end
  </code></pre>
  
  <p>Since some people might be skeptical whether there is a context in which manually deserializing the cookie can ever be proper:
  The client (browser) authenticates via HTTP, and the session is of course stored in the cookie. Rails is also running (rails runner) the websocket server that responds to certain privileged actions. For these I need to (re-)authenticate the user. If someone sees a different (better) way of doing that, I'd be glad to read it. :)</p>