Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add users with email only in Devise

I would like my users to be able to 'subscribe' by only providing an email address without forcing them to sign-up with a password unless they want to.

I can add my own validation settings to allow this but i suspect it will interfere with the way the rest of Devise works if i start adding users without passwords or flagging them with my own 'non-registered' field.

At the moment the easiest solution seems to put these users in a different table but that has a bit of a smell about it. Any ideas?

like image 613
Ian Avatar asked Apr 08 '11 13:04

Ian


2 Answers

I have an app that does something similar - we use Open ID and OAuth exclusively for logins, and while we store the user's email address (Google Account or Facebook sends it back during authentication) they never login using it and so don't have/need a password.

This is a callback for what happens when a user signs up via Facebook:

  User.create!( :facebook_id => access_token['uid'],
                :email => data["email"], 
                :name => data["name"], 
                :password => Devise.friendly_token[0,20])

The Devise.friendly_token[...] just generates a random 20 character password for the user, and we are using our default User model with devise just fine. Just setting the password in a similar way on your users would be my approach, since you are never going to use their password. Also, if you ever change your mind and want them to be able to login, you can just change a user's password in the database and build a login form, and devise will take care of the rest.

like image 98
Brett Bender Avatar answered Sep 21 '22 11:09

Brett Bender


Another option further to Brett's answer is to override the password_required? method on the User model.

def password_required?
    super && provider.blank?
end

If you store more than one omniauth provider then something like this should also work.

def password_required?
    super && self.omniauth_credentials.empty?
end

Full credit to Ryan Bates' railscast on Devise and Omniauth for this solution: http://railscasts.com/episodes/235-devise-and-omniauth-revised

like image 31
jonbeer Avatar answered Sep 19 '22 11:09

jonbeer