Tuesday, December 15, 2009

Authenticate your Authlogic users in Rails Metal

Update 2010-03-17: Don't fail in test mode if we can't find a user

I haven't been able to find any information on authenticating users in Rails Metal controllers. So I took a look at what was available in the session and worked with that. I'm not an expert on Authlogic (I did write an Authlogic Add-On a while ago) but this seems like a good solution. Let me know if you know of any problems with this approach.

I added a method to UserSession (or add it to whatever class you use for your sessions) that takes the Metal env and checks the authentication parameters and returns the user record. I don't bother with updating the user's last_request_at attributes or anything. I had to bypass the Authlogic session entirely because Authlogic needs to be activated with a controller before you can use the session stuff. I considered dummying the controller by including authlogic/test_case but I don't know enough about what the dummy controller does regarding authentication to go this route.

And the code...

Here's the Metal "controller":

A couple neat things in the Metal controller are the use of ActionController::Request.new(env) so we have access to request.remote_ip and other helper methods this class provides.

The part where I validate the user is:

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.