Anonymous users with Devise?

If I want to create a chat with rails (canonical case) with anonymous choice ("choose a nickname") and authorized (u / n and pw), how can I build it with Devise?

I successfully got Devise working in the latter case, this is the anonymous part (create and maintain a session) that I am struggling with.

+4
source share
4 answers

use additional before_filter to set an anonymous user, for example

def anonymous_sign_in return if user_signed_in? u = User.new(:type => 'anonymous') u.save(:validate => false) sign_in :user, u end 
+5
source

Actually there is a Wiki page for developers, only they call it a guest user:

How to create a guest user

+8
source

Another option is not to sign the guest user, but current_user returns the guest user in the absence of a signed user.

Below, if the user is not subscribed, then current_user will return the guest user. Thus, any controller that is accessed without access does not need authenticate_user! in front of the filter.

 def current_user super || guest_user end def guest_user User.find(session[:guest_user_id].nil? ? session[:guest_user_id] = create_guest_user.id : session[:guest_user_id]) end def create_guest_user token = SecureRandom.base64(15) user = User.new(:first_name => "anonymous", :last_name => 'user', :password => token, :email => "#{ token@example.com }") user.save(:validate => false) user end 
+4
source
 #user.rb # Creates an anonymous user. An anonymous user is basically an auto-generated # +User+ account that is created for the customer behind the scenes and its # completely transparently to the customer. def anonymous!(nickname) temp_token = SecureRandom.base64(15).tr('+/=', 'xyz') usr = ::User.new(email: "#{temp_token}@example.net", password: temp_token, password_confirmation: temp_token, nickname: nickname) usr.save!(validate: false) usr end 

You can then delete the entry when it fits.

+1
source

All Articles