Saturday, September 08, 2012

Devise: Logging in a user from a custom controller.

"Devise is a nightmare I have suffered only for the shining jewel called Omniauth clutched jealously within its thorny tentacles." -- a wild Arron under the influence of several frappucinos.

If you want to log in a user from a custom controller in Omniauth, this is your only hope:

user_params = params[:user] || {}

user = User.find_by_username(user_params[:username]) || User.find_by_email(user_params[:email])

if user && user.valid_password?(user_params[:password])
  sign_in :user, user
  # destroy the world.


You're probably thinking, "Can't I use warden.authenticate and cut down on the code and not have to do that nasty || at the beginning?"

No. See this question on StackOverflow for an explanation, but the short version is Devise doesn't want you to be able to use warden.authenticate anywhere outside of Devise::SessionController derived classes. Hilariously, if you go trolling for information on warden.authenticate you will find mostly unreplied to threads in Devise's Google Group, which is too many capitalized words in a row. If Google is a verb, can I refer to its products in lower case as well?

Goddamn. Does anyone remember Authlogic?

User#authenticate anywhere you wanted and you were fucking done, son. Yeah, Authlogic doesn't (or didn't) come with pre-built views like Clearance or Devise, which probably had a hand in it falling out of favor, but still, it was simple and almost impossible to screw up.

Theoretically you can get Omniauth up and running with anything, really, including Authlogic, but realistically setting up Facebook / Twitter login with Devise + Omniauth takes only seconds, and by the time you are screaming obscenities at your IDE it's too late to use anything else, assuming you even could -- I'm seeing that a lot of nifty stuff like rails_admin uses Devise under the hood.

Still hate the shit out of Devise for custom stuff, though.

That's right, hate. I am a mean coder. Rawr. Rawr!

Get out of here. Shoo.

No comments: