RoR Devise: Sign in with username OR email

前端 未结 11 2708
渐次进展
渐次进展 2020-12-07 10:15

What\'s the best way to enable users to log in with their email address OR their username? I am using warden + devise for authentication. I think it probably won\'t be too h

11条回答
  •  清歌不尽
    2020-12-07 10:32

    I use a quick hack for this, to avoid changing any devise specific code and use it for my specific scenario (I particularly use it for an API where mobile apps can create users on the server).

    I have added a before_filter to all the devise controllers where if username is being passed, I generate an email from the username ("#{params[:user][:username]}@mycustomdomain.com") and save the user. For all other calls as well, I generate the email based on same logic. My before_filter looks like this:

    def generate_email_for_username
        return if(!params[:user][:email].blank? || params[:user][:username].blank?)
        params[:user][:email] = "#{params[:user][:username]}@mycustomdomain.com"
    end
    

    I am also saving username in the users table, so I know that users with email ending in @mycustomdomain.com were created using username.

提交回复
热议问题