Better way to handle user id hash common to all rails requests

Each client is identified by a hash that is sent along with each request to the server. What is the best way to handle user session tracking in this case?

I am using restful_authentication for user accounts etc. A large percentage of requests are expected to occur without a user account, but only with a unique hash.

My understanding of how sessions are handled is limited, so keep that in mind. :)

+1


source to share


2 answers


Using this hash in the URL means you don't have an embedded Rails session. Session point is all about providing some sense of state between requests. You already provide this state by seeing that you are passing this hash, so in my opinion you can remove the restful_authentication plugin and do something like this:

class ApplicationController < ActionController::Base
  def require_login
    if params[:access_key]
      @current_user = User.find_by_access_key(params[:access_key]) || restrict_access
    else
      restrict_access
    end
  end

  def restrict_access
    flash[:error] = "You have to log in to access that."
    redirect_to root_path
  end
end

      



Then do a before_filter :require_login

in controllers where login is required to access.

+2


source


Depends on what you are trying to do, but the hash session

may provide what you want. The session is stored somewhere (either an encrypted cookie, or a database, or a file on the server) and sends a unique identifier to the client (similar to your "hash") in the cookie. On subsequent requests, the cookie is read and the corresponding user session data is restored to the hash << 20>.



session[:user] = currently_logged_in_user.id
# ... next request ...
session[:user] # returns the currently logged in user id

      

+1


source







All Articles