Log in by username or email in Authlogic
While I’m excited to see what the future holds for single sign-on systems, I don’t think we’re at the point where we can discard the traditional site registration paradigm, though, traditional user registration models still have a place in today’s ‘nets. One pain point I have with some sites is that I can never remember what username I used to register – sure, most of the time it’s the same one, but occasionally someone will have taken it before me. Other sites use your email address to log you in and do away with the concept of a username altogether. This is preferable as you’re not likely to forget your email address (and if you are, you’ve probably got bigger problems than being able to log in to some social site). Unfortunately, some sites have a real need for usernames, especially if users can interact with each other – you don’t want them to be able to see each other’s email addresses unless they’ve explicitly permitted it.
There’s a simple solution for this – let users log in with their username or email address. Earth-shattering, I know, but it’s the small things right?
I’ve been working on a small Rails site in my free time using the excellent Authlogic. This thing really simplifies a lot of the usual toil and drudgery associated with implementing a membership system, and lets you get back to the part where you can work on features.
It also lets you implement log in with username or email very easily:
user_session.rb:
class UserSession < Authlogic::Session::Base find_by_login_method :find_by_login_or_email end
user.rb:
class User < ActiveRecord::Base
def self.find_by_login_or_email(login)
User.find_by_login(login) || User.find_by_email(login)
end
end
That's it, you can also change your login page thusly:
views/user_session/new.html.erb:
<%= f.label :login, "Username or email address" %><br /> <%= f.text_field :login %>
And you're done! I love when things Just Work ™.
I found this on Stack Overflow, but it's probably somewhere in the Authlogic Documentation as well.