Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous users with Devise?

If I want to build a chatroom with rails (canonical case) with a choice of anonymous ('pick a nickname') and authorized (u/n & pw), how would I build this with Devise?

I've successfully got Devise working in the latter case, it's the anonymous part (create & maintain a session) I'm struggling with.

like image 684
cjm2671 Avatar asked Jul 18 '11 17:07

cjm2671


People also ask

Who is an anonymous user?

If you've ever used a website or app without creating or logging into an account, then you yourself may have been an anonymous user at one time or another.


3 Answers

There is actually a Devise Wiki page for that, only they call it Guest user:

How To: Create a guest user

like image 82
Art Shayderov Avatar answered Nov 10 '22 05:11

Art Shayderov


use extra before_filter to setup anonymous user, for instance,

def anonymous_sign_in
  return if user_signed_in?
  u = User.new(:type => 'anonymous')
  u.save(:validate => false)
  sign_in :user, u
end
like image 36
Anatoly Avatar answered Nov 10 '22 05:11

Anatoly


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

In the below if the user is not signed in then current_user will return a guest user. So any controller which can be access without signing in do not need the authenticate_user! before 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 => "#{[email protected]}")
  user.save(:validate => false)                                               
  user                                                                        
end   
like image 4
Kris Avatar answered Nov 10 '22 06:11

Kris