Devise的匿名用户?

时间:2011-07-18 17:11:24

标签: ruby-on-rails devise

如果我想建立一个带有rails(规范案例)的聊天室,可以选择匿名(“选择昵称”)和授权(u / n& pw),我将如何用Devise构建它?

我成功地让Devise在后一种情况下工作,这是我正在努力的匿名部分(创建和维护会话)。

5 个答案:

答案 0 :(得分:8)

实际上有一个Devise Wiki页面,只有他们称之为Guest用户:

How To: Create a guest user

答案 1 :(得分:5)

使用额外的before_filter来设置匿名用户,例如

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

答案 2 :(得分:4)

另一种选择不是登录访客用户,而是让current_user在没有登录用户的情况下返回访客用户。

在下面,如果用户未登录,则current_user将返回访客用户。因此,任何无需登录即可访问的控制器在过滤之前不需要authenticate_user!

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   

答案 3 :(得分:1)

#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

然后,您可以在适合的时候删除记录。

答案 4 :(得分:0)

这是我在Rails 6中所做的:

class ApplicationController < ActionController::Base
  before_action :anonymous_sign_in

  def anonymous_sign_in
    return if user_signed_in?

    u = User.new(:name => 'anonymous')
    u.save(:validate => false)
    sign_in :user, u
  end
end

从默认的devise生成模型中,我删除了电子邮件的default和null约束,并添加了名称:

class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :email
      t.string :name

      ## Database authenticatable
      # t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      # ...