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.
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.
There is actually a Devise Wiki page for that, only they call it Guest user:
How To: Create a guest user
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With