best way to handle user id hash common to all rails requests
-
23-08-2019 - |
Question
Each client is identified by a hash, passed along with every request to the server. What's the best way to handle tracking a users session in this case?
I'm using restful_authentication for user accounts etc. A large percentage of requests are expected to originate without a user account but just the unique hash.
My understanding of the way handles sessions is limited so please bear that in mind. :)
Solution
Using this hash in the URL means that you don't have Rails built-in session. The point of the session is to provide some sense of state between requests. You're already providing this state, seeing that you are passing this hash, so in my opinion you could remove the restful_authentication plugin and do something like this instead:
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 the controllers where login is required for access.
OTHER TIPS
Depends on what you're trying to do, but the session
hash might provide what you want. The session stores itself somewhere (either an encrypted cookie, the database, or a file on the server), and sends a unique identifier to the client (similar to your "hash") in a cookie. On subsequent requests, the cookie is read and the corresponding user's session data is restored to the session
hash.
session[:user] = currently_logged_in_user.id
# ... next request ...
session[:user] # returns the currently logged in user's id