rails 使用rucaptcha生成验证码

gem 'rucaptcha', '~> 2.4'

登录页面

<div class="code">
              <div class="form-group row string required code">
                <div class="col-sm-10">
                  <%= rucaptcha_input_tag(class: 'form-control', placeholder: '输入验证码', required: true) %>
                </div>
              </div>
              <div class="code-btn">
                <span><%= rucaptcha_image_tag(alt: '验证码,点击刷新', onclick: "this.src='/rucaptcha/?rand='+Math.random()") %></span>
              </div>
            </div>

登录验证

if !verify_rucaptcha?
      msg_action('验证码不正确')
      return redirect_to message_path
    end

redis缓存

gem 'redis', '~> 4.1'

在config/application.rb中增加缓存配置 

config.cache_store = :redis_cache_store, {url: Rails.configuration.application['REDIS_URL']}

在config/initializers目录下新增rucaptcha.rb

RuCaptcha.configure do
  # Color style, default: :colorful, allows: [:colorful, :black_white]
  # self.style = :colorful
  # Custom captcha code expire time if you need, default: 2 minutes
  # self.expires_in = 120
  # [Requirement / 重要]
  # Store Captcha code where, this config more like Rails config.cache_store
  # default: Read config info from `Rails.application.config.cache_store`
  # But RuCaptcha requirements cache_store not in [:null_store, :memory_store, :file_store]
  # 默认:会从 Rails 配置的 cache_store 里面读取相同的配置信息,并尝试用可以运行的方式,用于存储验证码字符
  # 但如果是 [:null_store, :memory_store, :file_store] 之类的,你可以通过下面的配置项单独给 RuCaptcha 配置 cache_store
  self.cache_store = :redis_cache_store
  # 如果想要 disable cache_store 的 warning,就设置为 true,default false
  # self.skip_cache_store_check = true
  # Chars length, default: 5, allows: [3 - 7]
  # self.length = 5
  # enable/disable Strikethrough.
  # self.strikethrough = true
  # enable/disable Outline style, for hard mode
  # self.outline = false
end

但是呢,使用file_store很正常,也能通过验证,但配置redis后,死活不通过验证,而使用redis.get(set)也没问题,网上转了一圈,基本me没有相关资料,无奈去看了下源码,发现在lib/rucaptcha.rb

 def config
      return @config if defined?(@config)
      @config = Configuration.new
      @config.style         = :colorful
      @config.length        = 5
      @config.strikethrough = true
      @config.outline       = false
      @config.expires_in    = 2.minutes
      @config.skip_cache_store_check = false

      if Rails.application
        @config.cache_store = Rails.application.config.cache_store
      else
        @config.cache_store = :mem_cache_store
      end
      @config.cache_store
      @config
    end

而我是把cache_store.redis直接配置在application.rb中的.

所以直接注释掉config/initializers/rucaptcha.rb里面的self.cache_store 就好。

#self.cache_store = :redis_cache_store

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值